在javascript中移动按钮

时间:2018-07-26 12:40:49

标签: javascript html css

幻灯片中有nextprev按钮,我希望它们在单击这些按钮后移动一些像素并更改其颜色。通过移开鼠标,按钮返回到正常位置。尽管我知道我可以使用CSS进行编码,但这是我作业的一部分,而我必须使用javascript来完成。这是我的代码,但是它不起作用,我也不知道为什么...

function press() {
    document.getElementById(this).style.right = "-10px";
    document.getElementById(this).style.backgroundColor = "red";
}
<a class="prev" onclick="plusSlides(1)" onmousedown="press()">&#10094;</a>
<a class="next" onclick="plusSlides(-1)" onmousedown="press()">&#10095;</a>

3 个答案:

答案 0 :(得分:4)

您需要将this传递给该函数,然后直接拥有该元素。

function press(element) {
    element.style.marginRight = "-10px";
    element.style.backgroundColor = "red";
}
<a class="prev" onmousedown="press(this)">&#10094;</a>
<a class="next" onmousedown="press(this)">&#10095;</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)">&#10094;</span>
<span onclick="applyStyles(this)" onmouseleave="revertStyles(this)">&#10095;</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)" >&#10094;</a>
<a id="next" class="next" onmousedown="press(this.id)">&#10095;</a>

您也可以通过将其作为函数参数传递来使其直接仅更改js函数:

function press(htmlElement){
    htmlElement.style.marginRight="-10px";
    htmlElement.style.backgroundColor="red";
}