好的,一个元素的边框出现在该元素的边框上。表示该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');
});
JS 小提琴演示。
编辑添加一个...凌乱(未优化)纯粹演示(和不推荐)的 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');
JS Fiddle 概念验证。
参考: