如果点击“vs-nav-right”或“vs-nav-left”,我喜欢将/ sub像素添加到“vs-wrapper”的背景位置。
我喜欢用纯JavaScript做到这一点,所以没有JQuery。
代码示例:
<div class="vs-wrapper" style="background-position: 0% 0%;"></div>
<ul>
<li class="vs-nav-right"></li>
<li class="vs-nav-left"></li>
</ul>
如果点击“vs-nav-right”,我想将50px添加到以下元素的背景位置
<div class="vs-wrapper" style="background-position: 50px 0;"></div>
再点击“vs-nav-right”,我想再添加50px
<div class="vs-wrapper" style="background-position: 100px 0;"></div>
与“vs-nav-left”相同,但不是添加50px我想减去50px
<div class="vs-wrapper" style="background-position: -50px 0;"></div>
答案 0 :(得分:1)
您可以这样做: -
$(document).on('click','.vs-nav-right',function(){
var m = document.getElementsByClassName("vs-wrapper");
var c = m[0].style;
if(c.backgroundPositionX == "0%")
c.backgroundPositionX = "0px";
c.backgroundPositionX = parseInt(c.backgroundPositionX) + 50 + 'px';
});
$(document).on('click','.vs-nav-left',function(){
var m = document.getElementsByClassName("vs-wrapper");
var c = m[0].style;
if(c.backgroundPositionX == "0%")
c.backgroundPositionX = "0px";
c.backgroundPositionX = parseInt(c.backgroundPositionX) - 50 + 'px';
});
答案 1 :(得分:0)
这对我很有用:
<div class="vs-wrapper" style="background-position: 0% 0%;"></div>
<ul>
<li class="vs-nav-right">Right</li>
<li class="vs-nav-left">Left</li>
<li class="vs-nav-up">Up</li>
<li class="vs-nav-down">Down</li>
</ul>
window.addEventListener('DOMContentLoaded', function() {
// Get the elements
var wrapper = document.querySelector(".vs-wrapper");
var navRight = document.querySelector(".vs-nav-right");
var navLeft = document.querySelector(".vs-nav-left");
var navUp = document.querySelector(".vs-nav-up");
var navDown = document.querySelector(".vs-nav-down");
// Pre-styling
wrapper.style.width = "200px";
wrapper.style.height = "200px";
wrapper.style.backgroundImage = "url(http://images.clipartpanda.com/rainbow-clip-art-rainbow.gif)";
// The main function
var changeBackgroundPos = function(ix, iy) {
var vals = wrapper.style.backgroundPosition.split(" ");
var x = parseInt(vals[0]) + ix + "px";
var y = parseInt(vals[1]) + iy + "px";
var newVals = x + " " + y;
wrapper.style.backgroundPosition = newVals;
};
// Adding changeBackgroundPos to each of the .vs-nav things
navRight.addEventListener('click', function() {
changeBackgroundPos(-40, 0);
});
navLeft.addEventListener('click', function() {
changeBackgroundPos(40, 0);
});
navUp.addEventListener('click', function() {
changeBackgroundPos(0, 40);
});
navDown.addEventListener('click', function() {
changeBackgroundPos(0, -40);
});
});
作为奖励,它也可以上下起伏。 ;)这是我使用的CodePen。