简体   繁体   中英

Fixing Flickering Text on .hover

I am displaying the alt tag information when the user hovers over the image. Here is the jQuery I'm using, which works well.

<script>
$("#content img").hover(function() {
    var imageCaption = $(this).attr("alt");
    if (imageCaption != '') {
        var imgWidth = $(this).width();
        var imgHeight = $(this).height();
        var position = $(this).position();
        var positionTop = (position.top + imgHeight - 26)
        $("<span class='img-caption'><em>" + imageCaption +
            "</em></span>").css({
            "font-style": "normal !important",
            "color": "#fff",
            "position": "absolute",
            "top": "200px",
            "left": "5px",
            "width": "80%"
        }).insertAfter(this);
    }},function(){$(this).siblings('.img-caption').remove();}
);
</script>

Its a little buggy though, when the user hovers over the text, the text flashes in and out. I assume its because the mouse is leaving the img and entering the span that has been created. Any solutions to this problem would be greatly appreciated.

jsFiddle : https://jsfiddle.net/m3h8bffw/

I have moved your element styles into the css file, no need to place inline styling when you can just target a class in your css file :) this will also enable you to easily change it

CSS

.img-caption {
  font-style: normal !important;
  color: #fff;
  position: absolute;
  top: 200px;
  left: 5px;
  width: 80%;
  pointer-events: none;
}

The only part you were missing is 'pointer-events', basically you can tell elements on the page to simply ignore events.

So now when the user mouses over the img, if the user then mouses over the span it will simply ignore mouse events.

http://caniuse.com/#feat=pointer-events https://developer.mozilla.org/en/docs/Web/CSS/pointer-events

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