我希望类中每个元素的左边距比最后一个边缘多70px左边距。即marginLeft + = 70px; 以下是我的尝试:
ruby -v
ruby 2.2.3p173 (2015-08-18 revision 51636) [x86_64-linux]
gem list
...
selenium-webdriver (2.48.1)
...
phantomjs -v
1.9.0

function MarginLeftFunc()
{
var elements = document.getElementsByClassName('divClass');
var i;
for(i=0; i<elements.length; i++)
{
elements[i].style.marginLeft += 70 + "px";
console.log(elements[i].style.marginLeft);
}
}
window.addEventListener('load', MarginLeftFunc, false);
&#13;
答案 0 :(得分:0)
您可以尝试使用方法getComputedStyle
,
Window.getComputedStyle()方法给出了所有CSS的值 应用活动样式表后元素的属性 解决这些值可能包含的任何基本计算。
因为element.style.marginLeft
没有显示来自CSS规则的样式。
function MarginLeftFunc() {
var elements = document.getElementsByClassName('divClass');
var i, marginLeft = 70;
for (i = 0; i < elements.length; i++) {
marginLeft += parseInt(window.getComputedStyle(elements[i]).marginLeft, 10) + 70;
elements[i].style.marginLeft = marginLeft + 'px';
}
}
window.addEventListener('load', MarginLeftFunc, false);
&#13;
.divClass {
margin-left: 10px;
}
&#13;
<div class="container">
<div class="divClass">Div1</div>
<div class="divClass">Div2</div>
<div class="divClass">Div3</div>
</div>
&#13;
答案 1 :(得分:0)
我认为这就是你要找的东西
function MarginLeftFunc()
{
var i;
var elements = document.getElementsByClassName('divClass');
var elementStyle = window.getComputedStyle(elements[0]);//gives the style of first element
var margleft =elementStyle.marginLeft;//get margin left value
margleft = margleft.replace("px", " ");//remove px
margleft = parseInt(margleft);//convert string to integer
for(i=0; i<elements.length; i++)
{
margleft+=70;
elements[i].style.marginLeft = margleft + "px";
console.log(elements[i].style.marginLeft);
}
}
window.addEventListener('load', MarginLeftFunc, false);
&#13;
.divClass {
margin-left: 10px;
}
&#13;
<div class="container">
<div class="divClass">Div1</div>
<div class="divClass">Div2</div>
<div class="divClass">Div3</div>
</div>
&#13;