更改 div 可见性并切换按钮文本的 Javascript 切换按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14085979/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript toggle button that changes div visibility, and toggles button text
提问by Kyle
This would be a great deal easier if I could use jQuery, but I'm trying to avoid doing so for a few reasons. Meanwhile, I've gotten some of the script to work - and I'm attempting to add the function to toggle the button text with the state of the div.
如果我可以使用 jQuery,这会容易得多,但我试图避免这样做,原因有几个。同时,我已经让一些脚本工作了 - 我正在尝试添加函数来切换按钮文本与 div 的状态。
<script type="text/javascript">
function toggleMe(a){
var e = document.getElementById(a);
if(!e) return true;
if(e.style.display == "none") {
e.style.display = "block"
} else {
e.style.display = "none"
}
return true;
}
</script>
That script works, and nicely, with my current button:
该脚本可以很好地与我当前的按钮配合使用:
<input type="button" onclick="return toggleMe('para0')" value="Expanse"><br>
<div id="para0">TEST TEXT</div>
Trying to have the text toggle with the state of the div visibility. Most answers I've seen are using jQuery, and the context I'm putting the script into makes forms a non-option.
试图让文本与 div 可见性的状态切换。我见过的大多数答案都使用 jQuery,而我将脚本放入的上下文使表单成为不可选项。
回答by elclanrs
See if this helps:
看看这是否有帮助:
HTML:
HTML:
<button id="toggle">Toggle</button>
<div id="text">Lorem ipsum dolor sit amet.</div>
JavaScript:
JavaScript:
var button = document.getElementById('toggle'),
text = document.getElementById('text');
button.onclick = function() {
var isHidden = text.style.display == 'none';
text.style.display = isHidden ? 'block' : 'none';
};
回答by catmom
My JS is a little rusty and I can't check this right now, but I think somthing like this will do what you want:
我的 JS 有点生疏,我现在无法检查,但我认为这样的事情会做你想做的事:
<input type="button" onclick="return toggleMe(this,'para0')" value="Expanse"><br>
<div id="para0">TEST TEXT</div>
<script type="text/javascript">
function toggleMe(btn,a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block";
btn.value = "Hide";
}
else{
e.style.display="none";
btn.value = "Show";
}
return true;
}
</script>
Fixed the spacing show /script would show.
修复了间距 show /script 会显示的问题。