如果窗口宽度小于768px,我正在尝试将元素移到画布菜单之外。
到目前为止,我有这个:
<script>
window.onresize = move_sidebar(event);
window.onload = move_sidebar(event);
function move_sidebar(event) {
if(window.outerWidth > 768) {
return;
} else {
console.log('resized or loaded');
document.getElementById('offcanvas-menu').appendChild(document.getElementById('sidebar-content'));
}
}
</script>
当窗口加载时,它工作正常,将显示控制台日志并移动元素,但是,当我调整窗口大小时,不会触发该事件。
除非我这样做:
window.onresize = function(event) { console.log('resizing'); };
每次调整窗口大小时,它都会记录下来,我无法弄清楚为什么两者之间会有区别。
如果宽度大于768px,我还需要将其移回其原始位置,只要它仅存在于offcanvas-menu元素中即可。
有任何想法吗?
编辑:
我最终使用以下代码修复了此问题:
<script>
window.onresize = move_sidebar;
window.onload = move_sidebar;
function move_sidebar(event) {
ele = document.getElementById('sidebar-content');
if(window.outerWidth > 768) {
if(ele.parentNode.id == 'offcanvas-menu') {
document.getElementById('sidebar').appendChild(document.getElementById('sidebar-content'));
}
return;
} else {
document.getElementById('offcanvas-menu').appendChild(ele);
}
}
</script>
你逝去的处理程序中的事件的结果,你move_sidebar
执行后发挥作用,而不是传递函数本身。
您的代码应为:
window.onresize = move_sidebar;
window.onload = move_sidebar;
页面加载时为您工作的原因仅仅是因为您错误地手动执行了功能。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句