【问题标题】:jquery change image src on rolloverjquery在翻转时更改图像src
【发布时间】:2014-09-27 23:56:55
【问题描述】:

我有两个图像和它们的翻转图像。使用 jQuery,我想在 onmousemove/onmouseout 事件发生时显示/隐藏翻转图像。我所有的图像名称都遵循相同的模式,如下所示:

Original Image: /CompleteEducation/images/icons/toggleIcon.png

Rollover Image: /CompleteEducation/images/icons/toggleIconDisabled.png

我使用了以下代码,但此代码覆盖了名称:

$(function() {
    $("img")
        .mouseover(function() { 
            var src = $(this).attr("src").match(/[^\.]+/) + "toggleIconDisabled.png";
            $(this).attr("src", src);
        })
});

我如何使用 jQuery 来做到这一点?

【问题讨论】:

标签: jquery image src


【解决方案1】:

我认为问题就在这里

 var src = $(this).attr("src").match(/[^\.]+/) + "toggleIconDisabled.png"; //this will return "/CompleteEducation/images/icons/toggleIcontoggleIconDisabled.png"

试试这个

var src = ($(this).attr("src").indexOf("Disabled")>-1)?"/CompleteEducation/images/icons/toggleIcon.png":"/CompleteEducation/images/icons/toggleIconDisabled.png";

【讨论】:

  • 答案和问题一样蹩脚。
  • @activehigh 你能说说真正的问题是什么吗?
  • 第一次用这段代码替换-var src = $(this).attr("src").replace("toggleIcon","toggleIconDisabled");,它会起作用,但是第二次将替换“toggleIcon”部分,因此输出将是-“toggleIconDisabledDisabled”。
【解决方案2】:

您可以使用条件运算符更改图像

$(function() {
    $("img")
        .mouseover(function() { 
            this.src = this.src.indexOf('Disabled.png') == -1 ?
               '/CompleteEducation/images/icons/toggleIconDisabled.png' :
               '/CompleteEducation/images/icons/toggleIcon.png';
        })
});

【讨论】:

    【解决方案3】:

    你说在每次鼠标悬停时,检查当前图像的属性 SRC 是否包含你喜欢的文件名。如果是,那么您更改来源。如果错误,您可以替换我的示例字符串。

    我的 HTML:

    <img src='http://velocityagency.com/wp-content/uploads/2013/08/go.jpg' width='500' >
    

    我的 JS:

    // 确保您已将代码放入 Document.ready
    $(document).ready(function(){

        $("img").on("mouseenter", function(){
    
    
        if($(this).attr("src").indexOf("go.jpg") !== -1) // we check if the path contains the name of the image at all
        {
           var att = $(this).attr("src"); // we then pull the src attr
           att = att.replace("go.jpg", "iPAd.jpg"); //and search for the filename and replace new file name
    
           // in the end we assign the new imagepath to the src of the hovered image
           $(this).attr("src", att);
        }
    });
    });
    

    检查这个小提琴或上面的代码:

    http://jsfiddle.net/F72h3/

    【讨论】:

    • 检查你的fireBug控制台或浏览器的控制台(F12)并报告错误。
    猜你喜欢
    • 2011-08-01
    • 1970-01-01
    • 2010-10-07
    • 2012-08-07
    • 2018-10-25
    • 2015-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多