如下图所示,我有一个简单的表单,可以实时验证字段并生成一个 span
来说明该字段是否有效。问题是,由于某种原因,即使它的 css 规则中有 position:absolute
,span 也不会扩展到包含的 div 之外。顺便说一句,跨度使用 javascript 获取其 right
位置,从而计算该字段的宽度(因为每个字段的宽度都不同)。有什么建议吗?
这是CSS代码:
div.row {
background:url('/img/formBackground.gif') repeat;
margin:0 2px 2px 2px;border-radius:10px 0 10px 0;
position:relative
}
.row span.valid,
.row span.invalid {
line-height:18px;
height:20px;padding:0 22px 0 5px;
display:block;font-size:13px;
border-radius:3px;position:absolute;
z-index:100;top:4px;right:160px
}
这是html代码:
<div class="row">
<label for="email">דואר אלקטרוני: <span class="required">*</span></label>
<div class="divider"></div>
<input type="text" name="email" id="email" style="width:250px" dir="ltr"/>
</div>
这是 JavaScript 代码:
email.onchange = function validateEmail() {
span = document.getElementById('span4');
span.style.right = calcDistance(email);
var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
el = email.value;
if(el == null || el == '') {span.setAttribute('class','invalid');span.innerHTML = "<span></span>עליך להזין דוא\"ל";return false;}
if(reg.test(el) == false) {span.setAttribute('class','invalid');span.innerHTML = "<span></span>כתובת הדוא\"ל אינה תקינה";return false;}
else {span.setAttribute('class','valid');span.innerHTML = "<span></span>תקין";return true;}
}
function calcDistance(el) {
var spanDistance = 160 + 20;
var targetWidth = el.offsetWidth;
return targetWidth + spanDistance + 'px';
}
这就是我想要的样子(span
延伸到包含的 div
之外)。我只能通过为 span
指定一定的 width
来获得此结果,这不是一个好的解决方案,因为每条消息的宽度都不同:
最佳答案
具有 position:relative
的元素将“捕获”任何绝对定位的子元素。换句话说,绝对元素的坐标是相对于父元素的。
- http://css-tricks.com/absolute-positioning-inside-relative-positioning/
- http://www.quirksmode.org/css/position.html (参见“包含 block ”部分)
虽然计算输入宽度来创建错误消息宽度很聪明,但这可能是一种过于脆弱的设计。您最终可能会收到对于消息本身而言太小的错误消息,尤其是当您认为自己无法真正 100% 控制用户的字体大小时。
此处没有足够的代码来重现图像中的输出,但可能的解决方案或解决方法可能包括:
- 从
div.row
中删除position:relative
- 更改您的设计,并将错误消息移至输入下方
关于javascript - CSS问题: absolute positioned span would not extend out of containing div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8583270/