对于以下示例,如何通过隐藏默认情况下当前显示的“divToToggle”DIV来关闭页面?我不想使用'display:none;'出于可访问性原因,在脚本之外。如何在启动时隐藏脚本中的'divToToggle'? 感谢。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JavaScript hide and show toggle</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
</head>
<body>
<script>
function toggleAndChangeText() {
$('#divToToggle').toggle();
if ($('#divToToggle').css('display') == 'none') {
$('#aTag').html('[+] Show text');
}
else {
$('#aTag').html('[-] Hide text');
}
}
</script>
<br>
<a id="aTag" href="javascript:toggleAndChangeText();">[-] Hide text</A>
<div id="divToToggle">Content that will be shown or hidden.</div>
</body>
</html>
答案 0 :(得分:0)
只使用jQuery,因为你已经在使用它(这种方式不会阻止非JS用户看到该元素):
function toggleAndChangeText() {
$('#divToToggle').toggle();
if ($('#divToToggle').css('display') == 'none') {
$('#aTag').html('[+] Show text');
}
else {
$('#aTag').html('[-] Hide text');
}
}
$('#divToToggle').hide();
// the rest of your script(s)...
此外,您的切换功能稍作更新:
function toggleAndChangeText() {
// because you're accessing this element more than once,
// it should be cached to save future DOM look-ups
var divToToggle = $('#divToToggle');
divToToggle.toggle();
// You're not changing the HTML, just the text, so use the
// appropriate method (though it's a *minor* change)
$('#aTag').text(function() {
// if the element is visible change the text to
// '...hide...'; if not, change the text to '...show...'
return divToToggle.is(':visible') ? '[-] Hide text' : '[+] Show Text';
});
}
参考文献:
答案 1 :(得分:0)
只需使用document.ready function
中的hide函数$(function(){
$('#divToToggle').hide();
});