我有li
元素,我使用javascriptposition:absolute
定位它们。transform:translate()
当浏览器窗口调整大小时,我需要重新定位它们,它工作正常,但是当媒体查询之间和之间的li
宽度发生变化时,元素在某些屏幕尺寸下无法正确定位,这是因为元素的实际与它不同中计算。50%
25%
width
javascript
HTML:
<div class="galleryList">
<ul>
<li class="filter-gallery">
<a href="#">
<img src="pics/g1.jpg" alt="">
</a>
</li>
<li class="filter-gallery">
<a href="#">
<img src="pics/g2.jpg" alt="">
</a>
</li>
<li class="filter-gallery">
<a href="#">
<img src="pics/g3.jpg" alt="">
</a>
</li>
<li class="filter-gallery">
<a href="#">
<img src="pics/g4.jpg" alt="">
</a>
</li>
<li class="filter-gallery">
<a href="#">
<img src="pics/g5.jpg" alt="">
</a>
</li>
<li class="filter-gallery">
<a href="#">
<img src="pics/g6.jpg" alt="">
</a>
</li>
<li class="filter-gallery">
<a href="#">
<img src="pics/g7.jpg" alt="">
</a>
</li>
<li class="filter-gallery">
<a href="#">
<img src="pics/g8.jpg" alt="">
</a>
</li>
</ul>
</div>
CSS:
img{
max-width:100%;
}
.galleryList ul{
position: relative;
}
.filter-gallery{
width: 50%;
position: absolute;
top:0;
left: 0;
overflow: hidden;
}
@media screen and (min-width: 620px) {
.filter-gallery{
width: 25%;
}
}
jQuery :
$(document).ready(function(){
var filterItems = $(".filter-gallery") ,
galleryList = $(".galleryList") ;
positionItems(filterItems);
function positionItems(filterItems){
var totalFilterItemswidth = 0 , rows = 0 , newI = 0 , useNewI= false ,
filterItemsHeight = filterItems.outerHeight() ,
filterItemsWidth = filterItems.outerWidth() ,
galleryListWidth = galleryList.outerWidth();
console.log(filterItemsWidth , filterItems[0]);
//positioning filter items
for(var i=0 ; i < filterItems.length ; i++){
var currentElement = $(filterItems[i]) ,
elementIndex = i ,
x ,
y = 0;
if(totalFilterItemswidth == galleryListWidth){ // 1 row completed
rows++;
totalFilterItemswidth = 0; //start adding widths again for next rows
newI = 0;
useNewI = true;
}
if(useNewI){
elementIndex = newI++;
}
y = filterItemsHeight * rows;
x = elementIndex * filterItemsWidth ,
currentElement.css({
transform: "translate(" + x + "px ," + y +"px )"
});
filterItemsWidth = filterItems.outerWidth();
totalFilterItemswidth += filterItemsWidth;
}
galleryList.css({
height : filterItemsHeight * (rows+1) + "px"
});
}
$(window).resize(function(){
positionItems(filterItems);
});
});
console.log()
在某些屏幕尺寸中显示的宽度与实际宽度不同627px
,当我再次调整窗口大小时,它工作正常。
我无法弄清楚为什么会发生这种情况以及如何解决它。
谢谢