使用JavaScript切换Google字体效果
我正在尝试为网页创建一个小的隐藏按钮,该按钮将在页面上的所有使用JavaScript切换Google字体效果,javascript,jquery,google-font-api,Javascript,Jquery,Google Font Api,我正在尝试为网页创建一个小的隐藏按钮,该按钮将在页面上的所有h1元素上切换,但我不完全确定如何进行,或者是否可行。这是我到目前为止的代码,这里的任何指导都将不胜感激 $(".flameOn").click(function(){ var $this = $(this); $this.find("h1").toggleClass("font-effect-fire"); }); .flameOn类附加到被点击的按钮上 问题可能在这里: $this.find("h1").toggl
h1
元素上切换,但我不完全确定如何进行,或者是否可行。这是我到目前为止的代码,这里的任何指导都将不胜感激
$(".flameOn").click(function(){
var $this = $(this);
$this.find("h1").toggleClass("font-effect-fire");
});
.flameOn
类附加到被点击的按钮上 问题可能在这里:
$this.find("h1").toggleClass("font-effect-fire");
实际上,您正在尝试在单击的flameOn类元素中查找h1元素,这当然没有意义。您可能只需要单击处理程序如下所示:
$(".flameOn").click(function(){
$("h1").toggleClass("font-effect-fire");
});
您遇到的问题与使用
this
搜索h1
标记有关。jQuery click处理程序将函数上下文(即this
)设置为单击的元素。在jQuery对象上调用find
方法时,它将尝试查找满足搜索条件的所有子节点
$('.flameOn').click(function(){
var $this = $(this); // In this context 'this' is the '.flameOn' button.
// You should also note that 'this', by default is
// already jQuery object, there is no need to wrap
// it in the $() again.
$this.find('h1') // This will almost certainly return an empty nodeList rather
// than all of the h1s on your page. At best it will return
// any h1s contained within the button.flameOn tag
});
本质上,您试图使用上述代码来查找.flameOn
类中的所有h1
s,因为它是一个按钮,所以没有多大意义
您真正想要的是简单地使用香草$
选择器查找所有h1
s并切换所需的类:
$('.flameOn').click(function(){
$('h1').toggleClass('font-effect-fire');
});
像这样的
<link href='http://fonts.googleapis.com/css?family=Didact+Gothic' rel='stylesheet' type='text/css'>
<script language="javascript">
function Style(enable) {
if (!document.getElementsByTagName) return;
links=document.getElementsByTagName("link");
links[0].disabled=!enable;
}
Style(true);
// disables font
Style(false);
// enables font
</script>
功能样式(启用){
如果(!document.getElementsByTagName)返回;
links=document.getElementsByTagName(“链接”);
链接[0]。已禁用=!启用;
}
风格(真实);
//禁用字体
风格(假);
//启用字体
::face palm::谢谢,这是一个非常简单的概念,因为某种原因,以前没有见过它。