使用Javascript将宽度添加到HTML元素 [英] Using Javascript to add width to a HTML element
问题描述
我试图用JavaScript函数修改 div
标签的位置和大小,并且困惑于如何引用div的当前宽度。
I am trying to work with altering a div
tag's position and size with a JavaScript function and am confused about how to reference the current width of the div.
这是我的函数
function socialExt()
{
document.getElementById("Left").style.width = ("Left").width+240px;
}
我想每次添加 240像素
I want it to add 240 pixels every time I click on the button.
- 我应该替换
(Left)width
ul>
- What should I replace
("Left").width
with in order to access its width so I can add 240px to it - I am also currently not using JQuery, should I use it?
推荐答案
快速和肮脏的jQuery版本:
Quick and dirty jQuery version:
$('#Left')。width(+ = 240);
strong>
Edit for use case in comments
if ($('#Left').width() < 640) {
$('#Left').width("+=240");
}
请检查文档以获取更多信息和示例。
Please check out the documentation for more information and examples.
请注意,在上面的示例中,如果你把 $('#Left')
提取出来放到一个变量中,效果会更好。这是更高效的b / c,你只需要查询一次DOM。这个可能不是你需要担心的,但它的好知道。修改后的示例如下:
Note that in my example above, it would be a bit more performant if you extracted $('#Left')
out into a variable. This is more efficient b/c you only have to query the DOM once. This probably isn't something you need to be worrying about, but its good to know. Revised example below:
var el = $('#Left');
if (el.width() < 640) {
el.width("+=240");
}
这篇关于使用Javascript将宽度添加到HTML元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!