有什么办法可以让列表项最初仅在桌面上显示,并且在更改屏幕大小时,列表项会动态更改为下拉列表项,您必须在其中单击 clickable heading
来显示内容吗?我想为此使用纯 JS。
<h2 class="clickable-heading">Toggle This Dropdown</h2>
<ul>
<li><a href="#">How To Do This</a>
</li>
<li><a href="#">Installing in The Mid 90s</a>
</li>
</ul>
<h2 class="clickable-heading">Click This Dropdown 2</h2>
JS:
function toggleDocs(event) {
if (event.target && event.target.className == 'clickable-heading') {
var next = event.target.nextElementSibling;
if (next.style.display == "none") {
next.style.display = "block";
} else {
next.style.display = "none";
}
}
}
document.addEventListener('click', toggleDocs, true);
这是我的 Fiddle .
PS:我知道 CSS
可以使用 checkbox hack,但我想避免这种情况。
最佳答案
您可以使用 window.innerWidth
和 window.innerHeight
获取窗口尺寸。
然后根据这些维度显示/隐藏 li
元素,如果隐藏它们,则将点击事件绑定(bind)到可点击的 h2
,这是工作代码:
function toggleDocs() {
var next = this.nextElementSibling;
if (next.style.display == "none") {
next.style.display = "block";
} else {
next.style.display = "none";
}
}
function checkWindowDimensions() {
var winWidth = window.innerWidth;
var winHeight = window.innerHeight;
console.log(winWidth + " ::: " + winHeight);
var ul = document.getElementsByTagName('ul')[0];
if (winWidth < 300 || winHeight < 300) {
ul.style.display = 'none';
document.getElementsByClassName("clickable-heading")[0].addEventListener('click', toggleDocs, true);
} else {
document.getElementsByClassName("clickable-heading")[0].removeEventListener('click', toggleDocs, true);
if (ul.nodeType == 1)
ul.style.display = 'block';
}
}
checkWindowDimensions();
window.onresize = function(event) {
checkWindowDimensions();
};
ul {
display: none;
}
<h2 class="clickable-heading">Toggle This Dropdown</h2>
<ul>
<li><a href="#">How To Do This</a>
</li>
<li><a href="#">Installing in The Mid 90s</a>
</li>
</ul>
<h2 class="clickable-heading">Click This Dropdown 2</h2>
这是 updated Fiddle .
关于javascript - 使用纯 Javascript 仅在移动设备上点击时显示列表内容,最初在桌面上显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32177689/