Jquery 计算div宽度并插入clear div
我有这个密码Jquery 计算div宽度并插入clear div,jquery,Jquery,我有这个密码 <div class="container"> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <div></div> <
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
container DIV的子项具有不同的高度,这意味着我会遇到float问题。我想要一些jquery,它可以查看孩子的宽度,计算它们,如果它们是100%或接近100%,则会在标记中添加一个带有清晰类的div
然而,我不知道如何开始。div都是百分比
更新:
对于响应性强的东西,我稍微修改了代码,这样就可以添加或删除它。我还让公司的一名javascript人员对其进行了优化
$(window).load(function () {
clearContext();
});
$(window).resize(function () {
clearContext();
});
function clearContext(){
$('.contextElements .spot').addLineBreak(); //Choose target
}
// PLUGIN
(function($) {
$.fn.addLineBreak = function() {
var $this = this,
minLeft = 0;
//clear
$('.removeDiv').remove();
minLeft = $this.first().position().left;
$this.each(function() {
var $elm = $(this),
position = $elm.position();
if (position.left > minLeft && $elm.prev().position().left >= position.left) {
$elm.before('<div class="clear removeDiv"></div>');
}
});
return this;
}
})(jQuery);
$(窗口)。加载(函数(){
clearContext();
});
$(窗口)。调整大小(函数(){
clearContext();
});
函数clearContext(){
$('.contextElements.spot').addLineBreak();//选择目标
}
//插件
(函数($){
$.fn.addLineBreak=函数(){
var$this=这个,
minLeft=0;
//清楚的
$('.removeDiv').remove();
minLeft=$this.first().position().left;
$this.each(函数(){
var$elm=$(此),
位置=$elm.position();
如果(position.left>minLeft&&$elm.prev().position().left>=position.left){
$elm.之前(“”);
}
});
归还这个;
}
})(jQuery);
width()
或outerWidth()函数计算.container
宽度
$('.container div')。每个(function(){})
计算每个div的宽度.after()
函数插入清除元素希望这会有所帮助。出于类似的目的,我不久前编写了这个插件:
(function($) {
$.fn.extend({
addLineBreak: function(css) {
var minLeft = $(this).position().left;
return $(this).each(function() {
var position = $(this).position();
if (position.left > minLeft && $(this).prev().position().left >= position.left) {
$(this).css(css);
}
});
}
});
})(jQuery);
用法:
$('.container div').addLineBreak({clear: 'left'});
演示:
在您的情况下,定义“接近”的含义。那么您希望将clearing div添加到哪里呢?使用jQuery/javascript解决布局问题是漫长黑暗道路上的第一步……看起来正是我所需要的。当我实现它时,我在控制台中得到一个错误。任何关于“uncaughttypeerror:cannotreadproperty'left'of null”@Johansrk的想法都可能是选择器匹配零元素。然后它会在
var minLeft=$(this.position().left)行中抛出此错误代码>。我对你的插件做了一些修改,因为IE7在清除div时遇到了问题。因此,它没有添加样式清除,而是在类中添加了一个divclear@Johansrk很高兴知道。谢谢!;)