我有这段jQuery,当用户将鼠标悬停在某个区域上时(使用imagemap),它会更改图像。
我想将其更改为单击功能,但仅将“悬停”更改为“单击”是不起作用。
我也怀疑点击版本可以大大简化。
jQuery:
<script>
$(document).ready(function() {
//set off state
var nav_off = "images/PWRwheel/000.png";
// functions for over and off
function over(image) {
$("#main-nav").attr("src", image);
}
function off() {
$("#main-nav").attr("src", nav_off);
}
$("#imagemap area").hover(
function () {
var button = $(this).attr("id");
over("images/PWRwheel/00" + button + ".png");
},
function () {
off();
});
});
</script>
HTML:
<map id="imagemap" name="imagemap">
<area id="8" shape="circle" coords="203,106,52" href="#" />
<area id="7" shape="circle" coords="99,207,52" href="#" />
<area id="6" shape="circle" coords="100,349,52" href="#" />
<area id="5" shape="circle" coords="200,459,52" href="#" />
<area id="4" shape="circle" coords="353,459,52" href="#" />
<area id="3" shape="circle" coords="454,350,52" href="#" />
<area id="2" shape="circle" coords="456,209,52" href="#" />
<area id="1" shape="circle" coords="352,103,52" href="#" />
</map>
要查看其当前的功能,请转到此处http://safespacetn.org/tools.html滚动到底部,然后单击“家庭暴力评估轮”之一。
当您想使用click
事件处理程序时,必须从监听器中踢出第二个函数。然后,代码将如下所示。
$("#imagemap area").on('click', function() {
console.log("hello")
var button = $(this).attr("id");
over("images/PWRwheel/00" + button + ".png");
});
});
jsfiddle:https://jsfiddle.net/e7qxhgfy/2/
要使此click
处理程序起作用,您需要更改逻辑,以便根据其当前值将新的src
提供给该元素。
也请注意,由于over()
和off()
函数都是单个代码行的包装,因此它们几乎完全是多余的,可以删除。试试这个:
jQuery(function($) {
let $nav = $('#main-nav');
let defaultSrc = 'images/PWRwheel/000.png';
$("#imagemap area").on('click', function() {
let src = $nav.attr('src') == defaultSrc ? "images/PWRwheel/00" + this.id + ".png" : defaultSrc;
$("#main-nav").attr("src", src);
});
});