使用JavaScript来递增上/左/下/右值 [英] Using JavaScript to increment top/left/bottom/right values
问题描述
我想通过 x 像素来增加元素的位置。这是我到目前为止尝试过的:
I am trying to increment the position of an element by, say, x pixels. Here is what I've tried so far:
var top = document.getElementById("something").style.top;
top = top + "300px"
我知道这不行,但我想知道是否可以增加这样的位置值。
I know that this is not going to work, but I was wondering if it was possible to increment a position value like this.
推荐答案
因为 top
是一个字符串,在它的末尾有单位像300px
你只能做数学,当你只转换数字部分
Because style.top
is a string with units on the end of it like "300px"
you can only do math with it when you convert just the numeric part to an actual number.
假设你有一个定位的元素(所以设置 top
值会做一些事情)已经在元素上直接设置了顶部
样式,而不是通过CSS设置(因此获取 obj.style.top
实际上是给你一些东西),你可以通过解析样式值的数字来做到这样:
Assuming you have a positioned element (so setting the top
value will do something) and you already have a top
style set directly on the element and not set via CSS (so getting obj.style.top
will actually get you something), you can do it by parsing the number out of the style value like this:
var obj = document.getElementById("something");
var topVal = parseInt(obj.style.top, 10);
obj.style.top = (topVal + 300) + "px";
工作范例: http://jsfiddle.net/jfriend00/pt46X/
这篇关于使用JavaScript来递增上/左/下/右值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!