幻灯片中有next
和prev
按钮,我希望它们在单击这些按钮后移动一些像素并更改其颜色。通过移开鼠标,按钮返回到正常位置。尽管我知道我可以使用CSS进行编码,但这是我作业的一部分,而我必须使用javascript来完成。这是我的代码,但是它不起作用,我也不知道为什么...
function press() {
document.getElementById(this).style.right = "-10px";
document.getElementById(this).style.backgroundColor = "red";
}
<a class="prev" onclick="plusSlides(1)" onmousedown="press()">❮</a>
<a class="next" onclick="plusSlides(-1)" onmousedown="press()">❯</a>
答案 0 :(得分:4)
您需要将this
传递给该函数,然后直接拥有该元素。
function press(element) {
element.style.marginRight = "-10px";
element.style.backgroundColor = "red";
}
<a class="prev" onmousedown="press(this)">❮</a>
<a class="next" onmousedown="press(this)">❯</a>
答案 1 :(得分:1)
function applyStyles(element) {
element.style.backgroundColor = 'red';
element.style.fontSize = '18px'
}
function revertStyles(element) {
element.style.backgroundColor = 'white';
element.style.fontSize = '15px'
}
<span onclick="applyStyles(this)" onmouseleave="revertStyles(this)">❮</span>
<span onclick="applyStyles(this)" onmouseleave="revertStyles(this)">❯</span>
答案 2 :(得分:-1)
本机函数getElementById
仅接受字符串作为参数,该字符串必须是您要迭代的html元素的“ id”。您的代码应如下所示:
function press(id){
document.getElementById(id).style.right="-10px";
document.getElementById(id).style.backgroundColor="red";
}
<a id="prev" class="prev" onmousedown="press(this.id)" >❮</a>
<a id="next" class="next" onmousedown="press(this.id)">❯</a>
您也可以通过将其作为函数参数传递来使其直接仅更改js函数:
function press(htmlElement){
htmlElement.style.marginRight="-10px";
htmlElement.style.backgroundColor="red";
}