简体   繁体   中英

Toggle a Google font effect with JavaScript

I am trying to create a small hidden button for a webpage that will toggle a Google font effect on all of the h1 elementss on the page but I'm not entirely sure how to go about it or if it's even doable. Here is the code I have so far, any guidance here would be greatly appreciated.

$(".flameOn").click(function(){
    var $this = $(this);
    $this.find("h1").toggleClass("font-effect-fire");
});

The .flameOn class is attached to the button being hit.

The problem is likely here:

$this.find("h1").toggleClass("font-effect-fire");

What you are, in effect, doing is trying to find h1 elements within the clicked flameOn class element, which of course makes no sense. You probably just need your click handler to look like this:

$(".flameOn").click(function(){
    $("h1").toggleClass("font-effect-fire");
});

The problem you are having has to do with the fact that you are using this to search for h1 tags. The jQuery click handler sets the function context (ie this ) to the clicked element. When you call the find method on a jQuery object, it will attempt to find all of the child nodes that meet your search criteria.

$('.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
});

In essence, what you are trying to do with the above code is find all of the h1 s inside of your .flameOn class, which doesn't make much sense given that it's a button.

What you really want is to simply use the vanilla $ selector to find all h1 s and toggle the class you want:

$('.flameOn').click(function(){
  $('h1').toggleClass('font-effect-fire');
});

Something like this?

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM