removing tooltip

2019-09-19 16:08发布

Is there a way to disable the default tooltip that shows up in a browser when hovering over an image? This is without removing the title or alt tags. Another option, can the tooltip be made to show a specific text for certain image types (such as JPG) and another text for a different image type (such as PNG)?

1条回答
一夜七次
2楼-- · 2019-09-19 16:32

The title attribute is used as hover text in most browsers by default. The only way I could see removing them is to remove the title attribute. JavaScript would be capable of doing this. I'm sure there is a pure DOM way to do this, but I'm using a little jQuery:

$(function() { // when the document becomes ready for manipulation
  $("[title]").removeAttr('title'); // removes title from all things that have title
  // your other options:
  // all images who's src ends in .jpg       
  $("img[src$=.jpg]").attr('title','JPG Image'); 
  // all images who's src ends in .png 
  $("img[src$=.png]").attr('title','PNG Image'); 
}

If you need to stick this on your pages, I suggest making a site.js file that has this code in it. Then you need to tell your HTML pages to load it. You should have some main site template file (and it may already have jQuery - if so skip the include for jQuery:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript" src="/js/site.js"> </script>

Response to comment: how about restricting the characters that can appear in the tooltip to zero or up to let's say 10?

This problem gets slightly more complicated, for this one lets pull out .each() on elements with titles:

 $("[title]").each(function() {
    var $this = $(this); // shortcut for later
    var title = $this.attr('title'); // get the title attribute
    // if the length of our title was 10 characters or more, shorten it and set:
    if (title.length>10) {
      $this.attr('title', title.substring(0,10));
    }
 });
查看更多
登录 后发表回答