さて、要素の境界線がその要素の境界線に表示されます。はその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');
JSFiddleの概念実証。
参照: