我有一段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 滚动到底部,然后单击“家庭暴力评估轮”之一。
答案 0 :(得分:1)
当您想使用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/
答案 1 :(得分:0)
要与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);
});
});