如何使用 javascript 在特定位置后添加 css border-right
。举个例子:
<div id="test"></div>
<style>
#test {
background-color : red;
height : 30px;
width : 200px;
}
</style>
我们可以使用 javascript 添加 css 样式,但是如果我想在 #test
中的 100px
之后添加 css border-right
那么我怎么才能去做。如示例 http://jsfiddle.net/zUxmd/1/我已经使用 javascript 添加了 css 边框,但是如果我想在特定的 px 值
之后添加它,我该怎么做。任何帮助都会很棒。
更新:
我有以下 div
结构
<div id=test>
<div id="1"></div>
<div id="2"></div>
<div>
#1
和#2
的宽度是在javascript 中计算的,宽度的总和设置为#test
。假设现在如果总宽度是 188px
我想在视觉上区分 100px
在哪里就像演示 http://jsfiddle.net/zUxmd/2/由 tom
编写。这是否可能以任何方式就像在该位置添加标记一样。但我不想添加任何额外的虚拟 div。
编辑:
演示 http://jsfiddle.net/davidThomas/zUxmd/7/ david
提出的正是我想要的。任何更好的想法将不胜感激。
最佳答案
好的,元素的边框出现在该元素的边框 上。 border
表示该元素的最外层边界,因此它不能出现在元素本身内,也不能与它出现的元素边的长度不同.
但是,也就是说,您可以通过 addClass()
和 ::after
伪元素笨拙地模拟您想要的东西:
CSS:
#test.amended {
width: 100px;
position: relative;
border-right: 2px solid blue;
}
#test.amended::after {
content: '';
position: absolute;
top: 0;
left: 102px;
bottom: 0;
display: inline-block;
width: 98px;
background-color: red;
}
jQuery:
$(document).ready(function(){
$('div').addClass('amended');
});
编辑以添加...凌乱(未优化)纯粹演示(且不推荐)的 JavaScript 解决方案:
function borderAt(el, pos) {
if (!el || !pos) {
return false;
}
else {
var pos = parseInt(pos, 10), // ensures a valid number (though there should be a sanity-check too)
w = el.clientWidth,
h = el.clientHeight,
nEl = document.createElement('div'),
pEl = document.createElement('div');
// adds a new 'parent' element to contain the elements
el.parentNode.appendChild(pEl);
// assigns the width of the specified 'el' element
pEl.style.width = w + 'px';
// appends the 'el' element to its new parent
pEl.appendChild(el);
nEl.style.backgroundColor = 'red';
// so the new sibling appears side-by-side
nEl.style.display = 'inline-block';
/* calculates the width required by the new-sibling element
in order to maintain visual continuity with the previous width */
nEl.style.width = w - (pos + 2) + 'px';
nEl.style.height = h + 'px';
el.style.borderRight = '2px solid blue';
el.style.width = pos + 'px';
el.style.display = 'inline-block'; // so the 'el' element appears side-by-side with its new sibling
// inserts new sibling after the 'el' element within its parent.
el.parentNode.insertBefore(nEl, el.nextSibling);
}
}
var el = document.getElementById('test');
borderAt(el, '160px');
引用资料:
- >
document.createElement()
. - >
element.clientHeight
. - >
element.clientWidth
. - >
node.appendChild()
. - >
node.insertBefore()
. - >
node.nextSibling
. - >
parseInt()
.
关于javascript - 在 div 中添加 css border-right,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10785352/