如何允许背景图像的水平滚动?



我正在制作简单的创意,当光标向左或向右拖动时,我想水平滚动div 的背景图像。

所以基本上我有宽度为 300px 的div,其背景图像大于div 宽度。 现在,每当您拖动或滑动图像时,图像都应相应地移动

这是代码:

<style>
.sprite-container {
width:300px;
float:left;
height:200px;
background-image: url("sprite.png");
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
background-attachment:scroll;
overflow-x: visible;
overflow: visible;
}
</style>
<div class="sprite-container"></div>

这是相同的jsfiddle链接:http://jsfiddle.net/janakprajapati90/gzLqspar/

您可以将 CSScalc()与单击时保存位置一起使用。然后计算鼠标移动的差异。

const vertical_scroll = false;
const horizontal_scroll = true;
(function(){
const scrolls = document.querySelectorAll(".sprite-container");
for(let i = 0; i < scrolls.length; i++){
initScrollable(scrolls.item(i), vertical_scroll, horizontal_scroll);
}
})();
function initScrollable(t, vertical_scroll, horizontal_scroll){
const init_bg_pos = [
getComputedStyle(t, null)["background-position-x"],
getComputedStyle(t, null)["background-position-y"]
];
let dragging = false;
let coords = [];
let offset = [0, 0];
t.addEventListener("mousedown", function(e){
dragging = true;
coords = [e.offsetX - offset[0], e.offsetY - offset[1]];
});
t.addEventListener("mouseup", function(){
dragging = false;
});
t.addEventListener("mousemove", function(e){
if(dragging){
offset = [e.offsetX - coords[0], e.offsetY - coords[1]];
t.style.backgroundPosition = 
(horizontal_scroll ? (
"calc(" + init_bg_pos[0] + " + " + offset[0] + "px)"
) : (
init_bg_pos[0]
)) + 
" " + 
(vertical_scroll ? (
"calc(" + init_bg_pos[1] + " + " + offset[1] + "px)"
) : (
init_bg_pos[1]
));
}
});
}
.sprite-container {
width:300px;
height:200px;
display: inline-block;
background-image: url("http://codeclippers.xyz/sprite.png");
background-size: cover;
background-repeat: no-repeat;
background-position: center center;
background-attachment:scroll;
overflow-x: visible;
overflow: visible;
}
<div class="sprite-container"></div>

我不确定在这里使用background-image是你想要的。 那又如何:

.img-container{
width: 300px;
/*height: 200px;*/ /* Probably not needed */
overflow: scroll;
}
<div class="img-container">
<img src="http://codeclippers.xyz/sprite.png">
</div>

引用 w3schools.com:

background-attachment属性设置背景图像是随页面的其余部分一起滚动还是固定。

如果没有内容溢出它,它不允许您滚动div。

最新更新