嗨,我仍然是jquery的新手。我尝试创建一个函数,我点击某个坐标,它将显示不同的图像。我的代码已经工作了。但我仍然试图使代码更清晰,更可重用。但我有点卡住了。我真的很感激,如果你们中的一个人想伸出援助之手,帮助我改进这些代码。谢谢
https://jsfiddle.net/ewtt0kzg/
$('.main-image').click(function(e) {
var main_image = $(this);
var topleft = $(this).siblings('.single-page-image').eq(0).attr('src');
var botLeft = $(this).siblings('.single-page-image').eq(1).attr('src');
var botRight = $(this).siblings('.single-page-image').eq(2).attr('src');
var topRight = $(this).siblings('.single-page-image').eq(3).attr('src');
var width = $(this).width();
var height = $(this).height();
var offset = $(this).offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
if (relativeY < (height / 2) && relativeX < (width / 2)) {
main_image.attr('src', topleft);
}
if (relativeY < (height / 2) && relativeX > (width / 2)) {
main_image.attr('src', topRight);
}
if (relativeY > (height / 2) && relativeX < (width / 2)) {
main_image.attr('src', botLeft);
}
if (relativeY > (height / 2) && relativeX > (width / 2)) {
main_image.attr('src', botRight);
}
});
&#13;
.second {
display: none;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="single-page">
<img class="single-page-image main-image" src="https://learn.getgrav.org/system/images/media/thumb-jpg.png" />
<img class="single-page-image second top-left" src="https://media.giphy.com/media/1bBMTxUs4iRTG/giphy.gif" />
<img class="single-page-image second bottom-left" src="https://webkit.org/demos/srcset/image-src.png" />
<img class="single-page-image second top-right" src="http://hubblesite.org/home-page/graphics/middle_container/Homepage-announce-gallery-400x400.png" />
<img class="single-page-image second top-left" src="http://static1.squarespace.com/static/560aa49ee4b0b632352fe46f/t/560d517de4b08ac155043394/1457617167699/" />
</section>
&#13;