3

我想创建一个平铺背景,其中背景的每一行都有一个随机的 x 偏移量。那将是理想的,但如果 CSS 无法做到这一点(我认为不是),那么至少使用单个图像创建主体背景的最佳方法是什么,其中该图像的这几行(比如说 4 行)具有不同的 x职位?

就像是:

图像图像图像图像
MAGEIMAGEIMAGEIMAGEI
AGEIMAGEIMAGEIMAGEIM
GEIMAGEIMAGEIMAGEIMA
图像图像图像图像
MAGEIMAGEIMAGEIMAGEI
AGEIMAGEIMAGEIMAGEIM
GEIMAGEIMAGEIMAGEIMA
4

2 回答 2

1

你的图像的大小是多少?如果它非常小,一个简单的解决方案是在 photoshop/paint 中做到这一点。生成的图像会大 4 倍,但对于小图像(读取小于 25ko),我认为这是迄今为止最简单的方法。至少我没有看到任何简单的 CSS 解决方案来解决您的问题。

如果您的图片很大并且您知道它的高度,您最终可以采用以下方法:http: //jsfiddle.net/7GPTy/

这个想法是在z-index:-1ofheight == image_height和绝对位置创建几个具有不同左值的 div ......我认为这是一个粗略但可行的解决方案

var mybody = document.getElementById('body');
var bodyHeight = mybody.offsetHeight;
var imgHeight = 49; // you could get the size by opening the file
var offsetLines = 4; // this is the number of offset you asked, but you can change that!
var nbOfLines = Math.ceil(bodyHeight/imgHeight);
for(var i=0; i<nbOfLines; i++){
    var newBgDiv = document.createElement('div');
    newBgDiv.className = 'backgroundImg imgOffset_'+(i%offsetLines);
    newBgDiv.style.top = (i*imgHeight) + 'px';
    newBgDiv.style.height = imgHeight + 'px';
    newBgDiv.style.width = '100%';
    mybody.appendChild(newBgDiv);
}

to go through the js code quickly, I basically get the height of the page and divide it by the height of the picture to know how many divs i have to create to generate the entire background. Once done, you simply define the number of different row offset you want (offsetLines) and you generate your divs.

In my example, the offset depends on the size of the window (try to resize horizontally your window, you'll see that the offset changes). You can of course fix it to a defined number of pixels !

于 2012-11-19T12:18:11.183 回答
0

If CSS3 is appropriate for your project, you can use multiple backgrounds to do this.

Make an image that is twice the height of your pattern, with the top half filled with your pattern, and the bottom half transparent.

Then use multiple backgrounds to position them accordingly like so:

.div {
    background: url(path/to/image.png) 0 0 repeat,
                url(path/to/image.png) 0 {height of image in pixel} repeat
}

Its not a random offset, but with enough variations to this, it would be hard to tell the difference.

If you want to add to the perceived randomness, have a look at this post.

于 2012-11-19T12:33:19.643 回答