使用纯Javascript显示列表内容仅在移动设备上点击并最初显示在桌面上

时间:2015-08-24 08:30:10

标签: javascript html css

我是否可以将列表项目最初仅在桌面上显示,并且在更改屏幕大小时,列表项会动态更改为下拉列表项,您必须单击 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可以使用复选框hack ,但我想避免这种情况。

1 个答案:

答案 0 :(得分:1)

您可以使用window.innerWidthwindow.innerHeight来获取窗口尺寸。

然后根据这些维度显示/隐藏li元素,如果你隐藏它们将click事件绑定到可点击的h2,这就是工作代码:

&#13;
&#13;
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();
};
&#13;
ul {
  display: none;
}
&#13;
<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>
&#13;
&#13;
&#13;

这是 updated Fiddle