JS:在悬停时更改图像名称

时间:2017-06-09 11:52:06

标签: javascript jquery css

我想添加' _hover.jpg'鼠标悬停在我的图像上,但我正在挣扎!任何帮助非常感谢。

<script type="text/javascript">
$(document).ready(function () {


$(".img").mouseover(function (e) {    
$(this).attr("src", $(this).attr("src").replace(".jpg", "_hover.jpg"));
}).mouseout(function (e) {
$(this).attr("src", $(this).attr("src").replace("._hover.jpg", ".jpg"));
});

)} 

<li class="hex">
<div class="hexIn">
<img src="/images/leaderboard.jpg" alt="" class="hex-img"/>
  <h2>Joe Bloggs<br>from ACME<br>volunteered at<br>Inspire<br>on 3 July</h2>
</div></li>

非常感谢

4 个答案:

答案 0 :(得分:1)

<style>
.hex-img:hover {
background-image: url('_hover.jpg');
}

.hex-img {
background-image: url('original.jpg');
}
</style>

答案 1 :(得分:1)

选择器错误,img而非.img。它代表了班级名称。但是你的班级名称是hex-imgdocument.ready没有正常关闭。关闭是错误的。它是})而不是)}

&#13;
&#13;
$(document).ready(function() {
      $("img").mouseover(function(e) {
        $(this).attr("src", $(this).attr("src").replace(".jpg", "_hover.jpg"));
        console.log($(this).attr("src"))
      }).mouseout(function(e) {
        $(this).attr("src", $(this).attr("src").replace("._hover.jpg", ".jpg"));
        console.log($(this).attr("src"))
      });
    })
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="hex">
  <div class="hexIn">
    <img src="/images/leaderboard.jpg" alt="" class="hex-img" />
    <h2>Joe Bloggs<br>from ACME<br>volunteered at<br>Inspire<br>on 3 July</h2>
  </div>
</li>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

&#13;
&#13;
$(".hex-img").mouseover(function () {    
$(this).attr("src", $(this).attr("src").replace(".jpg", "_hover.jpg"));
$(".test").text($(this).attr("src"));
}).mouseout(function () {
$(this).attr("src", $(this).attr("src").replace("_hover.jpg", ".jpg"));
$(".test").text($(this).attr("src"));
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="test">Hello</p>
<li class="hex">
<div class="hexIn">
<img src="abc.jpg" class="hex-img" width="100px" height="100px"/>
  <h2>Joe Bloggs<br>from ACME<br>volunteered at<br>Inspire<br>on 3 July</h2>
</div></li>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

当你调用默认的html标签时,你不需要添加.# ..但这不是一种专业方式..总是基于id或{{1改变这一行......

class