我昨天刚开始学习javascript,因为我真的需要一个代码来执行以下示例:(我只想到逻辑)
两个要素:
<div class="item bw" style="background-position: -10px -330px">
<div class="item bw" style="background-position: -10px -390px">
Javascript - 自动检测“bw”类状态(无任何手动触发)
Javascript - 获取background-position %y
值并存储到名为old-y
Javascript - 删除该数字后面的px
字符串(-330px变为-330)
Javascript - new-y = (old-y - 300) + "px"
(Y会消极,所以要添加一个我们需要减去的值)
Javascript - 将新的背景位置设置为元素
完成!
<div class="item bw" style="background-position: -10px -630px">
<div class="item bw" style="background-position: -10px -690px">
对不起。我只是想清楚我需要什么。
我使用此代码使用此工具:
window.onload = function()
{
var bws = document.querySelectorAll(".bw");
for (var i = bws.length-1; i >= 0; i-- )
{
var ypos, pos;
pos = bws[i].style.backgroundPosition.split(' ');
ypos = pos[1].match(/(-\d+)px$/);
bws[i].style.backgroundPosition = pos[0] + " " + (parseInt(ypos[1])-370)+"px";
}
};
这是基于Niet the Dark Absol的回答
答案 0 :(得分:1)
为什么你可以,尤其是因为初始值是在style
属性中定义的 - 这使得它比在CSS文件中更容易。
var bws = document.querySelectorAll(".bw"),
l = bws.length, i, pos, match;
for( i=0; i<l; i++) {
pos = bws[i].style.backgroundPosition || bws[i].style.backgroundPositionY;
match = pos.match(/(-\d+)px$/);
if( match) {
bws[i].style.backgroundPositionY = (match[1]-300)+"px";
}
}
完成!
答案 1 :(得分:0)
Ok, for this I will need the entire dom structure of your HTML page. But I will try to answer logically. (Hoping that I understood your question correctly)
1) Lets say we write a function startOnLoad(){}
2) Call this function in the body tag with event onLoad = "startLoading()"
3) Give and id to you <body> tag
4) Use var Parent = document.getElementById(<bodytagId>)
5) After this depending on the structure of the HTML dom parsing.
parentNode
childNodes
firstChild
lastChild
nextSibling
previousSibling
like Parent.nextSibling will give the next node.
eg: temp = Parent.nextSibling;
temp.id will return the id of the node. Store the value of id and do string comparison of 'btw'
6) if true, node use the following
Object.style.backgroundPosition to get or to set.
答案 2 :(得分:-2)
你可以使用jquery
$('.item.bw').css('background-position', newValue);
或仅Y值
$('.item.bw').css('background-position-y', newValue);