我想在 div 中隐藏和显示溢出内容。如果我单击展开按钮,它会展开。但我希望这个按钮应该切换并且文本也可以更改。谢谢
function descriptionHeightMore(){
var myElement = document.querySelector(".backwhite");
myElement.style.height = "auto";
}
.backwhite{
background-color: aqua;
padding:15px;
height:50px;
overflow:hidden;
}
<div class="container">
<div class="backwhite">
<p>1. Create Ui For Email Campaign.</p>
<p>2. Create Functionality of Email Campaign</p>
<p>3. Create Keyword Display using Drag And Drop Functionality.</p>
<p>1. Create Ui For Email Campaign.</p>
<p>2. Create Functionality of Email Campaign</p>
<p>3. Create Keyword Display using Drag And Drop Functionality.</p>
<p>1. Create Ui For Email Campaign.</p>
<p>2. Create Functionality of Email Campaign</p>
<p>3. Create Keyword Display using Drag And Drop Functionality.</p>
</div>
<button type="button" class="btn btn-default btn-block" onclick="descriptionHeightMore();">Expand</button>
</div>
最佳答案
这是一个使用纯 JavaScript 的解决方案
首先,您应该创建一个名为 .expanded
的新类,我们可以打开和关闭它 -
.backwhite.expanded {
height: auto;
}
接下来,我修改了 JavaScript 以切换 .expanded
类,以及按钮的内容 -
function toggleDescriptionHeight(e) {
// Toggle .expanded class
document.querySelector(".backwhite").classList.toggle('expanded');
// Toggle textContent of the button
e.target.textContent == 'Expand' ? e.target.textContent = 'Collapse' : e.target.textContent = 'Expand';
}
// Add event listener to button click
var button = document.querySelector('.btn');
button.addEventListener('click', toggleDescriptionHeight)
链接到 CodePen 上的工作示例 - http://codepen.io/ire/pen/wgyvYw
关于javascript - 如何通过文本更改在 JavaScript 中切换按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41952193/