简体   繁体   English

单击更改div的背景图像

[英]Change a background image of a div on click

Okay, I think my head is being dense. 好吧,我想我的头很密。 But I cant seem to get this to work. 但我似乎无法使它正常工作。 I'm doing a website for a photographer, and he wants to be able to let a user change the frame that they would like from a choice of 3. Easiest way I thought to do this was to create a div, and then have it change class based on a button click. 我正在为摄影师创建一个网站,他希望能够让用户从3的选择中更改他们想要的框架。我认为最简单的方法是创建一个div,然后使用它通过单击按钮更改类。 So it would change the background image. 因此它将改变背景图像。 However I cant get it to do this. 但是我无法做到这一点。 Any ideas would be well received, as I'm guessing theres probably a javascript version that does it quicker and easier. 任何想法都会受到欢迎,因为我猜可能会有一个javascript版本,它可以更快,更轻松地完成它。

<html>
<head>
<title>Untitled</title>
<style>
#pictureframe {
width:200px;
height:200px;
}

.wooden {
background-image:url(frame.png);
}

.plain {
background-image:url(clear.png);
}

.black {
background-image:url(black.png);
}

</style>
</head>
<body>

<div id="pictureframe">
</div>

<div style="height:20px;border:1px solid #617779;width:90px;text-align:center;background-color:white;" onclick = "pictureframe.style.className = 'wooden'">Make it wood</div>
<br>
<div style="height:20px;border:1px solid #617779;width:90px;text-align:center;background-color:white;" onclick = "pictureframe.style.className = 'clear'">Make it Frameless</div>
<br>
<div style="height:20px;border:1px solid #617779;width:90px;text-align:center;background-color:white;" onclick = "pictureframe.style.className = 'wooden'">Make it Black Bezel</div>
</body>

className不是DOM元素中style对象的一部分,而是直接属性:

document.getElementById("pictureframe").className = 'wooden';

It's not 不是

pictureframe.style.className = ...

but

pictureframe.className = ...

DEMO 演示

尝试这个:

onclick ="pictureframe.className = 'wooden'"

If you want to use some other class for style, than you probably need to go with something like this: 如果您想使用其他类作为样式,则可能需要执行以下操作:

function replaceClass(className) {
    $('#pictureframe').removeClass('plain black wooden');
    return $('#pictureframe').addClass(className);
}​

This way you can keep class with styles http://jsfiddle.net/NjTea/5/ 这样,您可以使用样式http://jsfiddle.net/NjTea/5/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM