gpt4 book ai didi

javascript - 在方向更改、导航和 li 元素固定或静态时更改布局

转载 作者:太空宇宙 更新时间:2023-11-04 13:05:01 25 4
gpt4 key购买 nike

是否可以在方向更改时更改布局 reliably and cross browser只使用 CSS/媒体查询?我不认为它甚至在最新的浏览器中,是吗?

查看人们试图仅使用 CSS 以及 device-heightdevice-width 可靠地确定纵向和横向方向跨浏览器的许多问题 being deprecated我认为最好建议我使用 JavaScript 执行此操作,对吗?

类似于this question我正在尝试根据纵向和横向方向更改导航布局。

肖像

Portrait

风景

Landscape

这是我使用 JavaScript 和 VergeJS 的方法(因为它可靠地检测视口(viewport)高度和宽度),然后我将类应用于 li 元素以根据需要定位它们,检查 body 是否具有 portraitlandscape 类分配,然后在横向时检查视口(viewport)高度。

// Cross browser portrait landscape detection

// Get viewport width and height values
// http://stackoverflow.com/q/40672125/1010918
function getVergeValues(){
viewportWidth = verge.viewportW()
viewportHeight = verge.viewportH()
console.log('viewportWidth = '+viewportWidth);
console.log('viewportHeight = '+viewportHeight);
};
getVergeValues();
window.addEventListener('resize', getVergeValues);

// http://pioul.fr/cross-device-cross-browser-portrait-landscape-detection
function portraitLandscape(){
screenOrientation = (viewportWidth > viewportHeight)? 90 : 0;
console.log('screenOrientation = '+screenOrientation);
if (screenOrientation == 0) {
body.classList.add('portrait');
body.classList.remove('landscape');
}
else if (screenOrientation == 90) {
body.classList.remove('portrait');
body.classList.add('landscape');
}
};
portraitLandscape();
window.addEventListener('resize', portraitLandscape);

CSS/SCSS 看起来像这样。

// Landscape layout for navigation on mobile
ul{
li{
// depending on number of li elements I would also
// have to change the width values, assigning a grid of some sort.
// again I assume this can ONLY be done with JS reliably??
width: 33.3333333333%;
display: inline-block;
float: left;
a{
border-right: 1px solid black;
}
}
li:last-child a {
border-right: none;
}
}

// Portrait layout for navigation on mobile
ul {
padding: 0;
li {
list-style: none;
display: block;
margin: 0;
float: none;
width: 100%;
a {
display: block;
}
}
}

为什么会这样?
导航是 fixedtop:0 并且在点击/单击菜单按钮时 li 元素向下滑动,这些也是 固定

我想避免横向 li 元素不可访问,因为它们超出了视口(viewport)高度。请注意 li 元素的数量也有所不同,因此未设置,并且因为它们都是固定的,所以如果它们很多,可能永远无法在横向方向上到达它们。我不希望用户必须转动设备才能看到所有 li 元素,并且完全将网站浏览方式的选择权留给用户。

作为代码更少并且可能更容易实现的替代方案,如果横向视口(viewport)高度小于包含所有 li 元素的导航高度?

是的,我很客气地不仅询问这是否可以仅在 CSS 中完成,而且还询问您是否可以使用 A) 为 li 元素制作网格并保持它们 fixed 或 B) 定位导航和 li 元素 static 如果其中有很多,则首选。

最佳答案

CSS 媒体查询还可以检测横向或纵向方向,而无需 JavaScript 开销。

@media only screen and (orientation: landscape) {
.class-name {
declaration: value;
}
}

@media only screen and (orientation: portrait) {
.class-name {
declaration: value;
}
}

使用媒体查询,您将编写更少的代码,并且当方向发生变化时,浏览器将负责重新呈现您的页面。

关于javascript - 在方向更改、导航和 li 元素固定或静态时更改布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43635632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com