Javascript 使用jQuery或JS增加元素宽度
因此,我有多个元素的类名为Javascript 使用jQuery或JS增加元素宽度,javascript,jquery,html,css,width,Javascript,Jquery,Html,Css,Width,因此,我有多个元素的类名为ml,由于不同的文本内容(未在CSS中设置),所有元素的宽度都不同。 例如: <li><a class="depth ml" title="">Login</a></li> 什么也没发生 我尝试使用offsetWidth和clientWidth var curr_width = parseInt(elems[i].offsetWidth); 但它几乎增加了40px,我不知道这些是从哪里来的。这些元素上甚至没有空格或边距
ml
,由于不同的文本内容(未在CSS中设置),所有元素的宽度都不同。
例如:
<li><a class="depth ml" title="">Login</a></li>
什么也没发生
我尝试使用offsetWidth
和clientWidth
var curr_width = parseInt(elems[i].offsetWidth);
但它几乎增加了40px,我不知道这些是从哪里来的。这些元素上甚至没有空格或边距
我只想添加元素的内部宽度
有人能提出解决方案吗,或者看看jQuery为什么不起作用
编辑:
以下是标记:
<body>
<div id="master_container">
<div class="container">
<div id="body">
<header>
<div id="homelink"></div>
<div id="links" class="topmenulist">
<ul id="nav" class="title">
<li><a class="depth ml" title="home">Home</a></li>
<li><a class="depth ml" title="BBTV1">BBTV1</a></li>
<li><a class="depth ml" title="BBTV">BBTV</a></li>
<li><a class="depth ml" title="About us" style="">About us</a></li>
</ul>
</div>
</header>
注意:.ml没有css只是要指出,您使用的是纯JS-您真勇敢;)无论如何,使用jQuery,您可以尝试以下方法:
$(window).load(function() {
$(".ml").each(function() { // this is kindof sugary way of doing for loop over array of elements - which is $(".ml")
var $this = $(this); // the current jQueried .ml element
var currentWidth = $this.width(); // get width of current element, width is a jQuery method: https://api.jquery.com/width/
var newWidth = currentWidth + 5; // increment the width
$this.width(newWidth); // pass in the new width as the parameter.
});
});
在代码中:
var curr_width = elems[i].width();
解析为未定义的值,因为DOM对象没有width
属性(只有jQuery对象有此属性)
因此,下一条语句(curr\u width+num)
是不正确的,因为您想用一个数字添加一个未定义的值。这并不是真正的解决方案。但是谢谢你指出这个问题。我仍然比我应该得到的多40像素。。知道为什么会发生这种情况吗?你能发布你的标记吗?也许你有嵌套的.ml
元素?很有趣,似乎工作正常,这里有一个快捷的提琴:它显示了所有.ml
元素在递增前后的宽度。看一看。顶部菜单中的项目是.ml
。我将宽度设置为-=15,但它们比原始宽度大了近30px。可能在时页面仍在应用css样式。调用每个方法?你能试试我答案中的更新片段,看看这是否有区别吗?
$(window).load(function() {
$(".ml").each(function() { // this is kindof sugary way of doing for loop over array of elements - which is $(".ml")
var $this = $(this); // the current jQueried .ml element
var currentWidth = $this.width(); // get width of current element, width is a jQuery method: https://api.jquery.com/width/
var newWidth = currentWidth + 5; // increment the width
$this.width(newWidth); // pass in the new width as the parameter.
});
});
var curr_width = elems[i].width();