我有两张图片需要在点击图片时切换。
<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png'
data-src='images/prof_arrow1.png' />
当用户点击图片时,src
应获得data-swap
的值,当您再次点击时,src
应更改为data-src
。这应该像切换一样继续发生。任何帮助赞赏。
$("#arrowRotate").click(function() {
var swapImage = $("#arrowGrey").attr("data-swap");
$("#arrowGrey").attr({
'src': swapImage,
id: 'arrowOrange'
});
});
这是我到目前为止的地方。
答案 0 :(得分:7)
根据我对你问题的理解,希望这是你期望的那个,
$("#arrowRotate").click(function() {
var _this = $(this);
var current = _this.attr("src");
var swap = _this.attr("data-swap");
_this.attr('src', swap).attr("data-swap",current);
});
<强> DEMO Fiddle 强>
答案 1 :(得分:3)
试试这个:
$("#arrowRotate").click(function(){
if($(this).attr('src')==$(this).attr('data-src'))
{
var a = $(this).attr('data-swap');
$(this).attr('src',a);
}
else
{
var b = $(this).attr('data-src');
$(this).attr('src',b);
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id='arrowRotate' src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg' data-swap='http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg' data-src='http://www.gettyimages.in/CMS/StaticContent/1391099215267_hero2.jpg'>
&#13;
答案 2 :(得分:1)
这可能会有所帮助。我认为这是在图像之间交换的最简单方法:
<img id="arrowRotate" src="images/img1.png" data-swap="images/img2.png" data-src="images/img1.png" onclick="swapImage()" />
function swapImage(){
var swapImage = $('#arrowRotate').attr('data-swap'),
currentImage = $('#arrowRotate').attr('src');
$('#arrowRotate').attr({
'src': swapImage,
'data-swap': currentImage
});
};
答案 3 :(得分:0)
如果我理解你,你可以这样做:
<强> HTML 强>
<img id='arrowRotate' src='images/prof_arrow1.png' data-swap='images/prof_arrow.png' data-src='images/prof_arrow1.png' data-swapped="false"/>
<强>的Javascript 强>
$("#arrowRotate").click(function() {
var swapped = $(this).attr("data-swapped");
var init = 'false';
if(swapped === 'false'){
var swapImage = $(this).attr("data-swap");
init = true;
}else{
var swapImage = $(this).attr("data-src");
}
$(this).attr({
'src': swapImage,
'id': 'arrowOrange',
'data-swapped': init
});
});