【问题标题】:JQuery change img src on hover doesnt work悬停时 JQuery 更改 img src 不起作用
【发布时间】:2018-01-19 19:36:44
【问题描述】:

我正在尝试使用 JQuery 更改悬停时的 img src。 我正在使用括号,当我运行实时 Chrome 预览时,一切都很好。 但是当我直接在 Chrome 上打开文件时它不起作用(与 IE 相同)。

我的代码:

$("#logo img").hover(
    function(){
              $("#logo img").attr("src","/images/img1.gif");
 }, function() {
              $("#logo img").attr("src","/images/img2.gif");
}); 

编辑: 这是 HTML 代码:

<div id="logo">
    <img id="logo-img" src="images/img1.gif" alt="logo">
</div> 

img 标签有一个 id “logo-img”,但直接使用这个 id 并没有帮助:

$("#logo-img").hover(
    function(){
              $("#logo-img").attr("src","/images/img1.gif");
 }, function() {
              $("#logo-img").attr("src","/images/img2.gif");
}); 

感谢您的帮助。

【问题讨论】:

  • 请张贴引用#logo img...的html代码...但我建议您为img提供一个类或ID以直接访问它,例如:$('.elementClass)。悬停
  • 请给我包含代码和img的文件路径。
  • 您的身份证真的无效?您不能在其中使用空格。还为此提供 HTML。你的 JQuery 很好。
  • 另外,您在使用 chrome 打开时是否在正确的目录中提供了图像?

标签: jquery html css


【解决方案1】:

它应该工作。试试这个:

$("#myImage").hover(function(){
  $(this).attr("src", "https://static.pexels.com/photos/54630/japanese-cherry-trees-flowers-spring-japanese-flowering-cherry-54630.jpeg");
}, function(){
  $(this).attr("src", "https://static.pexels.com/photos/207962/pexels-photo-207962.jpeg");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img id="myImage" src="https://static.pexels.com/photos/207962/pexels-photo-207962.jpeg">

尝试运行它。可能是您的图像 ID 有问题。也可以使用$(this) 使其更容易。

【讨论】:

  • 欢迎您!考虑将其标记为已接受的答案,方法是单击否决标志下答案左侧的灰色勾号。
【解决方案2】:

使用 CSS

img:hover {
  background: url("https://i2.wp.com/www.froutlet.com/store/i/user_icon.png?ssl=1");
  /* padding: [image-height] [image-width] 0 0 */
  padding: 200px 200px 0 0;
  width: 0;
  height: 0;
}
&lt;img src="https://www.vacul.org/extension/site/design/site//images/anonymous-user.png" /&gt;

使用 JS

$("#imghover").hover(function(){
  $(this).attr("src", "https://www.vacul.org/extension/site/design/site//images/anonymous-user.png");
}, function(){
  $(this).attr("src", "https://i2.wp.com/www.froutlet.com/store/i/user_icon.png?ssl=1");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img id="imghover" src="https://i2.wp.com/www.froutlet.com/store/i/user_icon.png?ssl=1">

【讨论】:

    猜你喜欢
    • 2016-08-07
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-20
    相关资源
    最近更新 更多