当我按下键盘上的按钮时,我正在尝试更改一组图像的类别( a )。我写了以下代码:
<div id="images" class="img"/>
<img src="spiderman.png" alt=""/>
<img src="superman.png" alt="" height="25%" width="25%"/>
<img src="batman.png" alt="" />
</div>
<Script type="text/javascript">
function keyDown(event) {
if (event.keyCode == 65) {
var canvas = document.getElementById('images');
canvas.innerHTML = '<img class="img2" />'
}
}
function keyUp(event) {
if (event.keyCode == 65) {
var canvas = document.getElementById('images');
canvas.innerHTML = '<img class="img" />';
}
}
</script>
CSS
.img {
position: absolute;
right: 15%;
top: 30%;
display: flex;
flex-direction: column;
align-items: flex-end;
}
.img2 {
box-shadow: 0px 0px 5px #fff;
position: absolute;
right: 15%;
top: 30%;
display: flex;
flex-direction: column;
align-items: flex-end;
}
我对html和JavaScript都很陌生,所以不知道为什么这不起作用,或者即使我在html中正确使用了JavaScript,我试图实现的是什么呢?正确方向上的一点将有所帮助:)
答案 0 :(得分:1)
在您的代码中,您不会替换元素类。您正在替换图像本身。如果你想改变clas,请使用:
document.getElementById("MyElement").className = "MyOtherClass"
所以它会是这样的:
(function() {
function keyDown(event) {
if (event.keyCode == 65) {
if (document.getElementsByClassName("img").length > 0) {
document.getElementsByClassName("img")[0].className = "img2"
} else {
document.getElementsByClassName("img2")[0].className = "img"
}
}
}
document.addEventListener('keydown', keyDown);
})();
.img {
width: 100px
}
.img2 {
width: 400px
}
<img class="img" src="http://www.axpe-blogs.com/wp-content/uploads/stackoverflow_logo.jpg" />