jQuery:悬停时更改img

标签 jquery background hover

我使用 jQuery 背景拉伸(stretch)器,其中背景设置为图像,其 id="bg"位于正文之后。但后来我想在有人将鼠标悬停在带有 class=selector 和 alt=pathToImage 的 div 时更改背景图像。 我知道 alt 不是在 div 中使用的最佳选择,但我需要找到一个“容器”来存储路径。

背景拉伸(stretch)器完全符合其应有的要求,但是当我将鼠标悬停在某物上时,它将背景图像设置为display =“none”。 我真的希望有人能帮助我。

代码是:

$(window).load(function(){
$('.selector').hover(function() {
    var img = document.createElement('img');
    img.src = $(this).attr('alt');
    img.onload = function() {
        $('#bg').fadeOut(function() {
            $(this).setAttribute('src', img.src).fadeIn();
        }); }; return false; }); });

提前谢谢你:)

编辑! 抱歉花了这么长时间,但让 html 阅读起来不那么痛苦: http://jsfiddle.net/gaFfD/ 由于某些奇怪的原因,悬停效果在 jsfiddle 中不起作用。

最佳答案

更新

试试这个 fiddle :http://jsfiddle.net/gaFfD/14/

应该是

$(this).attr('src', img.src).fadeIn()

而不是

$(this).setAttribute('src', img.src).fadeIn();

我用过

jQuery(document).ready(function () {

而不是

$(window).load(function() {

文档就绪和窗口加载之间的区别: window.onload vs $(document).ready()

关于jQuery:悬停时更改img,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10909997/

相关文章:

javascript enter 事件在谷歌上不起作用

android - MenuScene 上的 RepeatingSpriteBackground

javascript - 将鼠标悬停在链接上后 Mouseenter 失败

hover - 边框样式不适用于顺风悬停

ios - Swift如何使用NSTimer后台?

html - CSS - 悬停时文本 move

javascript - 如何改进这一小段代码

javascript - 如果以(this)作为参数,如何每秒调用函数或在加载元素时调用函数?

jQuery .show() 向元素添加样式 ="display:inline-block"

Swift - 后台蓝牙写入特性