单击添加或删除类-Javascript

时间:2019-07-17 19:19:58

标签: javascript html css

我试图在单击框时添加一个类,然后在单击按钮时删除该类。但是没有添加或删除任何类。

var leftBox = document.getElementsByClassName("left");
var rightBox = document.getElementsByClassName("right");

function expandLeft() {
  leftBox.className = leftBox.className + "zero-width";
  rightBox.className = rightBox.className + "full-width";
}
function expandRight() {
  leftBox.className = leftBox.className + "full-width";
  rightBox.className = rightBox.className + "zero-width";
}

function originalLeft(){ 
  leftBox.removeClass(leftBox, "zero-width");
  rightBox.removeClass(rightBox, "full-width");
}

function originalRight(){ 
  leftBox.removeClass(rightBox, "full-width");
  rightBox.removeClass(leftBox, "zero-width");
}



<div class="row">
<div class="wrapper flex full-width">
<div class="form_wrapper flex full-width">
<div class="left">
<div class="form_wrapper--left" onclick="expandRight()">
<div><button id="shrink" onclick="originalLeft()">click here</button> . 
</div>
</div>
</div>
<!-- END OR RIGHT BOX --
<!-- START OR RIGHT BOX -->
<div class="right">
<div class="form_wrapper--right" onclick="expandLeft()">
<div>
<button id="shrink" onclick="originalLeft()">click here</button>
</div>
</div>
</div>
<!--- END of Right Box --->
</div>
</div>
</div>

效果应该是:单击一个框时,它会向左扩展,然后单击一个按钮,它将返回。反之亦然。

2 个答案:

答案 0 :(得分:0)

尝试一下:

document.getElementById("test").addEventListener("click", enlarge);
document.getElementById("btn").addEventListener("click", resume);

function enlarge() {
  document.getElementById("test").classList.add("enlarge");
}

function resume() {
  document.getElementById("test").classList.remove("enlarge");
}
#test {
  width: 100px;
  height: 100px;
  background-color: green;
  margin-bottom: 20px;
}

.enlarge {
  transform: scaleX(2);
}
<div id="test"></div>

<button id="btn">
  Resume
</button>

答案 1 :(得分:0)

您可以在jQuery中使用.toggleClass()

也许此链接有帮助: https://api.jquery.com/toggleclass/