是否可以使用jQuery/javascript每隔x个像素重复放置一个DIV

Is it possible to use jQuery/javascript to place a place a DIV repeatedly every x pixels

本文关键字:DIV 一个 像素 jQuery 可以使 javascript 每隔 是否      更新时间:2023-09-26

我的问题是这个。我有一个DIV,它使用CSS3复制图像。这个Div需要在页面的一侧以设定的间隔重复。即每200像素。有没有办法实现自动化。通常我会使用一个重复的bgimage,但在这种情况下,不允许使用任何图像。我也可以每次重复div,但这是一个很大的页面,会经常更新更多的内容。

任何想法都将不胜感激。

我会这样做:

文档高度/元素高度+200px=x在文档中放置元素X次。

就是这样。

在jQuery中,这看起来像这样:

在这里试试:http://jsfiddle.net/aF68z/

var repeatMe = function ( $o, space ){
  var oHeight,dHeight, multiplicator, res, html, $parent;
  dHeight = $(document).height(); //height of you document
  oHeight = $o.height(); //height of the element that shoud repeat 
  multiplicator = Math.floor(dHeight / (oHeight + space)); //how many time the element can repeat (including the margin)
  $parent = $o.parent(); //gets the parent that finally will hold all repeating items
  html = $parent.html(); //gets the HTML code of the element that repeats
  /* appending and cloning are very CPU heavy and it makes no sense to do so only for a visual matter, "string" + "string" etc... is very slow if the string becomes long, this is a simple trick how to avoid this: */
  res = [];  
  for (var i = 0; i < multiplicator; ++ i) {
    res.push(html);
  }
  html = res.join("");

  $parent.html(html); //appending the HTML of the all the repeated elements to the parent again.
};
repeatMe( $("div.deco div:eq(0)"),200 );

附言:下次至少自己试试吧。

使用

.yourClass{
       width:200px;
       height:yourHeightValue;
}
.imgClass{
       text-align:center;
}

并根据需要添加任意数量的CCD_ 1。

如果你需要垂直重新吃div,你可以做:

.yourClass{
       height:200px;
       width:whatyouwant;
}
var numberOfDivs = 8;//chose the number you want or calculate it
var div = $('<div>', {class: 'yourClass'});//create your div
for (i=0; i < numberOfDivs ; i++){
     $('.leftSidebar').append(div);
}

如果我没有误解你的问题,这可能会有所帮助。

var times = 10;
var elementToRepeat = $('.myDiv'); 
var lastElement = elementToRepeat;
for(var i = 0 ; i < times ; times++){
   var newElement = elementToRepeat.clone();
   lastElement.after(newElement);
   lastElement = newElement;
}

此外,为div的类设置一个底部边距,以便它们具有所需的分隔。

$('.myDiv').append($('.myDiv').clone())

并给div一个200像素的页边空白底部样式

编辑:对于那些抱怨它不是一个循环和嵌套的Divs

for(i=0;i<10;i++)
{
    $('.myDiv').after($('.myDiv').clone().removeClass('myDiv')) 
}