javascript – 连续背景图像模式的几个元素
作者:互联网
我需要在几个元素上形成连续的背景模式.
我无法控制元素的高度或数量.
这是一个例子:
p{
margin:0;
padding:1.5em;
}
.bg{
background-image:url('http://enjoycss.com/webshots/hB_1.png');
}
<p>some text<br>on several lines</p>
<p class="bg">some text<br>on several lines</p>
<p class="bg">some text<br>on several lines<br><br>and another<br>some text<br>on several lines<br><br>and another</p>
<p class="bg">some text<br>on several lines<br><br>and another</p>
<p>some text<br>on several lines<br><br>and another<br>some text<br>on several lines<br><br>and another</p>
<p class="bg">some text<br>on several lines</p>
<p class="bg">some text<br>on several lines<br><br>and another<br>some text<br>on several lines<br><br>and another</p>
<p class="bg">some text<br>on several lines<br><br>and another</p>
我正在寻找的效果几乎是通过background-attachement实现的:fixed;但是我需要背景来滚动内容.
例:
p{
margin:0;
padding:1.5em;
}
.bg{
background-image:url('http://enjoycss.com/webshots/hB_1.png');
background-attachment:fixed;
}
<p>some text<br>on several lines</p>
<p class="bg">some text<br>on several lines</p>
<p class="bg">some text<br>on several lines<br><br>and another<br>some text<br>on several lines<br><br>and another</p>
<p class="bg">some text<br>on several lines<br><br>and another</p>
<p>some text<br>on several lines<br><br>and another<br>some text<br>on several lines<br><br>and another</p>
<p class="bg">some text<br>on several lines</p>
<p class="bg">some text<br>on several lines<br><br>and another<br>some text<br>on several lines<br><br>and another</p>
<p class="bg">some text<br>on several lines<br><br>and another</p>
解决方法:
使用Javascript
使用少量JavaScript,您可以获得所需的效果.
此方法获取当前高度并添加所有先前的高度,以便为元素提供其起始背景位置.
var lastHeight = 0;
$('.bg').each(function() {
$(this).css('background-position', '0 -' + lastHeight + 'px');
var currentHeight = $(this).outerHeight();
var newPosition = currentHeight + lastHeight;
lastHeight = lastHeight + currentHeight;
});
p {
margin: 0;
padding: 1.5em;
}
.bg {
background-image: url('http://enjoycss.com/webshots/hB_1.png');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>some text<br>on several lines</p>
<p class="bg">some text<br>on several lines</p>
<p class="bg">some text<br>on several lines<br><br>and another<br>some text<br>on several lines<br><br>and another</p>
<p class="bg">some text<br>on several lines<br><br>and another</p>
<p>some text<br>on several lines<br><br>and another<br>some
<p class="bg">some text<br>on several lines</p>
<p class="bg">some text<br>on several lines<br><br>and another<br>some text<br>on several lines<br><br>and another</p>
<p class="bg">some text<br>on several lines<br><br>and another</p>
<p>some text<br>on several lines<br><br>and another<br>some text<br>on several lines<br><br>and another</p>
标签:javascript,jquery,css,background,background-image 来源: https://codeday.me/bug/20190727/1555514.html