function change(element) {
document.getElementById('imageReplace').src = element;
}
function change_1() {
document.getElementById('1').style.background = '#111';
document.getElementById('1').style.color = '#FFF';
document.getElementById('1').style.cursor = 'auto';
document.getElementById('2').style.background = '#FFC300';
document.getElementById('2').style.color = '#FFF';
document.getElementById('2').style.cursor = 'pointer';
document.getElementById('3').style.background = '#FFC300';
document.getElementById('3').style.color = '#FFF';
document.getElementById('3').style.cursor = 'pointer';
}
function change_2() {
document.getElementById('2').style.background = '#111';
document.getElementById('2').style.color = '#FFF';
document.getElementById('2').style.cursor = 'auto';
document.getElementById('1').style.background = '#FFC300';
document.getElementById('1').style.color = '#FFF';
document.getElementById('1').style.cursor = 'pointer';
document.getElementById('3').style.background = '#FFC300';
document.getElementById('3').style.color = '#FFF';
document.getElementById('3').style.cursor = 'pointer';
}
function change_3() {
document.getElementById('3').style.background = '#111';
document.getElementById('3').style.color = '#FFF';
document.getElementById('3').style.cursor = 'auto';
document.getElementById('1').style.background = '#FFC300';
document.getElementById('1').style.color = '#FFF';
document.getElementById('1').style.cursor = 'pointer';
document.getElementById('2').style.background = '#FFC300';
document.getElementById('2').style.color = '#FFF';
document.getElementById('2').style.cursor = 'pointer';
}
.row_1 {
float: left;
}
<div class="row_1">
<button id="1" onclick="change('somepic.jpg'); change_1()">1</button>
<button id="2" onclick="change('somepic2.jpg'); change_2()">2</button>
<button id="3" onclick="change('somepic3.jpg'); change_3()">3</button>
</div>
我是新来的... 刚刚启动我的网站并尝试了一些 JavaScript 编码。
有趣的是,当在 Firefox 中打开时,它在 Adobe Dreamweaver CS6 中运行得非常好。
但是,当它放入我的网站管理器(我的网站如何放到互联网上)时,它的运行速度非常慢......
请帮忙。我怀疑代码一定太长了,但是我尝试了很多方法,它并没有按照我想要的方式显示...
正如您可能已经猜到的,我正在尝试制作一个在单击时更改样式的按钮,而其他按钮将恢复默认样式...
提前致谢!
最佳答案
不要重复使用document.getElementById()
。这个不成立。每次执行此操作时,您都会在 DOM 中搜索节点。
所以代替这个:
function change_3() {
document.getElementById('3').style.background = '#111',
document.getElementById('3').style.color = '#FFF',
document.getElementById('3').style.cursor = 'auto'
}
这样做
var three = document.getElementById('3');
function change_3() {
three.style.background = '#111',
three.style.color = '#FFF',
three.style.cursor = 'auto'
}
关于javascript 执行时间太长,让观众等待太久,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44847129/