【发布时间】:2014-12-04 13:59:29
【问题描述】:
我正在使用(div 可能是更好的选择,但目前我正在使用框架)建立一个网站。它由 menu.html 和 main.html 组成。 Main.html 分别更改为 menu.html 中点击了哪个按钮。
menu.html - 大约 9 个按钮 - 每个按钮有 3 个相关图像 - 默认(xxx.jpg) - 鼠标悬停时 (xxx_hover.jpg) - 点击时(xxx_onclick.jpg)
目标 1. mouseover 时图像更改,mouseout 时返回默认值 2. 点击时图片会发生变化,并保持点击状态,直到点击另一个(在同一框架内)
到目前为止我所拥有的... 我不知道如何保持图像保持为 xxx_onclick.jpg 直到另一个被点击。另外,使用下面的代码,我得到一个错误;当我将鼠标悬停在单击的图像上时,它会尝试查找不存在的 xxx_onclick_hover.jpg。我不确定我应该使用什么功能。
<head>
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
</head>
<body>
<img class="menu_btn" src="button1S.jpg"><br>
<img class="menu_btn" src="button2S.jpg"><br>
<img class="menu_btn" src="button3S.jpg"><br>
<img class="menu_btn" src="button4S.jpg">
</body>
<script>
$(".menu_btn")
.mouseover(function() {//onmouseover
this.src = this.src.replace('.jpg', '_hover.jpg');//replace src link from .jpg to _hover.jpg
})
.mouseout(function() {//onmouseout
this.src = this.src.replace('_hover.jpg', '.jpg');//replace src link from _hover.jpg to .jpg
})
.click(function() {//onclick
$(".menu_btn").unbind('mouseover');//disable mouseover to prevent error (ie. button1S_onclick_hover.jpg), but this disable all images...
this.src = this.src.replace('_hover.jpg', '_onclick.jpg');//onclick reply _hover.jpg to _onclick.jpg
}
);
</script>
非常感谢您。
以下是根据 Joce 的建议测试的一组代码 *尚未 100% 正常运行。
<html>
<head>
<style type="text/css">
.menu-btn {
background: url('http://icdn.pro/images/en/s/m/smiley-smile-icone-8052-128.png') no-repeat center;
width: 128px;
height: 128px;
display: inline-block;
}
.menu-btn:hover {
background: url('http://www.baza-lesnik.ru/images/blobwars.png') no-repeat center;
}
.menu-btn.active {
background: url('http://cdn.flaticon.com/png/256/40230.png') no-repeat center;
}
</style>
</head>
<body>
<a href="#" class="menu-btn"></a>
<a href="#" class="menu-btn"></a>
<a href="#" class="menu-btn"></a>
<a href="#" class="menu-btn"></a>
<a href="#" class="menu-btn"></a>
</body>
<script type="text/javascript">
$(function() {
$(".menu-btn").on("click", function(e) {
e.preventDefault();
$(".menu-btn.active").removeClass("active");
$(this).addClass("active");
//Do more things
});
});
</script>
</html>
【问题讨论】:
-
不要直接在 Javascript 中更改图像源,而是更改
img元素的类并将所需的图像分配给每个类。 -
帕特里克,感谢您的建议。我相信你的建议是乔斯的回答。非常感谢。
标签: jquery html button onclick mouseover