Javascript 方向更改时更改元素的偏移量(jQuery/CSS)
我有一个div,我想根据div的大小和形状以及图标的大小和数量动态排列图标。我首先编写了一些代码,将第一个图标放在div的中心,然后我计划相对于第一个图标安排其余图标 在这一点上,我只是想让中心的第一个图标工作。我可以让它在初始页面加载时工作,但当我改变屏幕方向时,它不再位于中心 我尝试为“orientationchange”添加一个侦听器并再次调用arrangeIcons()函数,但它不起作用。我还尝试延迟调用arrangeIcons()函数,以防在div上更新offset属性之前调用它 我在div上有一个边框,以验证当方向改变时它是否正在调整大小 我不想重新加载整个页面,只想重写div的内容 我希望这是有道理的 我已经在下面包括了我的css和js JS CSSJavascript 方向更改时更改元素的偏移量(jQuery/CSS),javascript,jquery,html,css,responsive-design,Javascript,Jquery,Html,Css,Responsive Design,我有一个div,我想根据div的大小和形状以及图标的大小和数量动态排列图标。我首先编写了一些代码,将第一个图标放在div的中心,然后我计划相对于第一个图标安排其余图标 在这一点上,我只是想让中心的第一个图标工作。我可以让它在初始页面加载时工作,但当我改变屏幕方向时,它不再位于中心 我尝试为“orientationchange”添加一个侦听器并再次调用arrangeIcons()函数,但它不起作用。我还尝试延迟调用arrangeIcons()函数,以防在div上更新offset属性之前调用它 我在
这里有一个指向我工作的钢笔的链接:不要忽略你已经做过的工作,但是你确定这是JS的工作,而不是基于的媒体查询吗?这是一个好问题,我必须研究它以获取更新。但是对于这个项目,我主要关注css和js/jquery。
$( document ).ready(function() {
// call arrangeIcons() after page loads to
// arrange them on the screen
arrangeIcons();
// when orientation changes, call arrangeIcons()
// again to re-arrange the icons -- NOT WORKING
$(window).on("orientationchange", function() {
alert(screen.orientation);
arrangeIcons();
});
// Find the center of the div and arrange the
// icons based off of it
function arrangeIcons() {
// leftCoord is the "top" property plus half the width of the div
// minus half the width of the icon
var leftCoord =
($('.icon-holder').offset()["top"] +
($('.icon-holder').width()*.5)) -
$('.dev-icons').width()*.5;
// topCoord is the "left" property plus half the height of the div
// minus half the height of the icon
var topCoord =
($('.icon-holder').offset()["left"] +
$('.icon-holder').height()*.5) -
$('.dev-icons').height()*.5;
// set the offset of the icon
$('.dev-icons').offset({
"top" : topCoord,
"left" : leftCoord
});
}
});
.dev-icons {
font-size: 5vw;
}
.icon-holder {
border: solid 1vw;
height: 200vw;
max-height: 300px;
}