我希望在使用jQuery悬停在src
上时更改图片<p>
,例如http://mdpoison.com/主页中的新闻部分。 (试着徘徊在&#34的主题上;你知道吗?&#34;)
我在这个页面代码中看到html就像:
<p data-val="/media/SOP/mdpoisoncom/homepage/didyouknow/CarbonMonoxideDidYouKnow.jpg" class="">
Families can help prevent poison-related injuries this winter by following the MPC’s <a href="http://mdpoison.com/media/SOP/mdpoisoncom/education/pdf/WinterPoisonSafety_2014.pdf">winter poison safety tips</a>.
</p>
当你将鼠标悬停在它上面时,它会添加一个名为dky-active
的类。我不知道如何添加此类并使用jQuery切换新的src
。
我看到这样的代码:
$('ul.small img').hover(function ()
{
$('.inner img').attr('src' ,$(this).attr('src'));
});
但在我的情况下没有用,因为我想切换图片。
答案 0 :(得分:2)
您可以使用css ~ selector。
通过使用它,它避免使用javascript并将其全部推送到css选择器:
.wrapper {
height: 500px;
width: 500px;
background: red;
}
.myImg {
height: 300px;
width: 300px;
background: url(http://placekitten.com/g/200/300); /*original placeholder*/
}
.wrapper .ptag1:hover ~.myImg {
background: url(http://placekitten.com/g/300/200); /*first paragraph hovered*/
}
.wrapper .ptag2:hover ~.myImg {
background: url(http://placekitten.com/g/300/300); /*second paragraph hovered*/
}
&#13;
<div class="wrapper">
<p class="ptag1">I'm a paragraph. Hover Me!!</p>
<p class="ptag2">I'm a paragraph. Hover Me too!!</p>
<div class="myImg"></div>
</div>
&#13;
答案 1 :(得分:1)
你可以这样做:
<强> HTML 强>
<div class="content">
<p data-img="http://www.wired.com/wp-content/uploads/images_blogs/rawfile/2013/11/offset_WaterHouseMarineImages_62652-2-660x440.jpg">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
<p data-img="http://imageswiki.com/wp-content/uploads/2014/11/images-Photoshop-Image-of-the-horse-053857-.jpg">Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur</p>
</div>
<div class="picture">
<img src="" id="picture" width="200" height="200" />
</div>
<强> JQUERY 强>
$('p').mouseover(function () {
$('#picture').attr('src', $(this).data('img'));
});
<强> FIDDLE EXAMPLE 强>
答案 2 :(得分:0)
$('p').on('mouseover',function(){
$('img').attr('src',"http://lorempixel.com/200/200/sports/2");
});
$('p').on('mouseout',function(){
$('img').attr('src',"http://lorempixel.com/200/200/sports/1");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Hover me to change the image</p>
<img src="http://lorempixel.com/200/200/sports/1" width="200" height="200">