[英]Get the background image for a button and change it
I have a one row table that contains a series of buttons. 我有一个包含一系列按钮的单行表。 Each button has its own unique image.
每个按钮都有自己独特的图像。 As the user hovers over each button, I want to change the image.
当用户将鼠标悬停在每个按钮上时,我想更改图像。 All my images are pre-loaded, so now I'm just working on the part where I iterate over the collection, determine its image, and change that image.
我所有的图像都是预加载的,所以现在我只需要对集合进行迭代,确定其图像并更改该图像。 First the HTML:
首先是HTML:
<table><tr id='menu_row'>
<td id='home'>
<button id='btn_home' onclick="btnHome()">
<img src="images/home_green.png">
</button>
</td>
<td id='capabilities'>
<button id='btn_capabilities' onclick="btnCapabilities()">
<img src="images/capabilities_green.png">
</button>
</td>
...
</tr></table>
I'm successful with identifying the collection since my console output matches what I would expect. 由于控制台输出与我期望的相符,因此我可以成功识别出该集合。 But I'm stuck on capturing the image.
但是我坚持要捕获图像。 This code doesn't throw any errors, but it doesn't switch the image, either
此代码不会引发任何错误,但也不会切换图像
$("#menu_row").find('button').hover(function() {
flipColor(event.target.id);}
);
function flipColor(btn_id) {
console.log(btn_id); // this shows the correct output
// this is where things go south
var image = document.getElementById(btn_id);
// this will expand into a switch statement eventually
image.src = home_blue.src;
}
The object home_blue.src
is instantiated in a preloader function: 对象
home_blue.src
在预加载器函数中实例化:
home_blue = new Image();
home_blue.src = "http://www.xxxxx.com/images/home_blue.png";
If there are better approaches, I'd appreciate hearing about them. 如果有更好的方法,我将不胜感激。 Thanks!
谢谢!
If you're going to use jQuery, use jQuery: 如果要使用jQuery,请使用jQuery:
$("#menu_row").find('button').hover(function () {
flipColor(this.id);
});
function flipColor(btn_id) {
$('#'+btn_id).find('img').prop('src', home_blue.src);
}
Instead of adding the background image to the button like that and using jQuery or Javascript to change it, use CSS, like this: 不用像这样向按钮添加背景图像并使用jQuery或Javascript对其进行更改,而应使用CSS,如下所示:
HTML: HTML:
<button id='btn_home' onclick="btnHome()" />
CSS: CSS:
#btn_home {
background:url('images/home_green.png');
}
#btn_home:hover {
background:url('images/home_blue.png');
}
By the way, you'd better add a class to each button and use the class in your CSS file, instead of the id. 顺便说一句,您最好向每个按钮添加一个类,并在CSS文件中使用该类而不是id。 That way, you can reuse the background image for several buttons.
这样,您可以将背景图像重用于多个按钮。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.