如何编写HTML输入的JS内联

How to write a JS inline of HTML input?

本文关键字:JS 内联 输入 何编写 HTML      更新时间:2023-09-26

我有一个浏览器检查:

$(document).ready(function() {
if ($.browser.chrome) {
  //show document write input only if chrome = true else, ignore it
}
});
</script>

HTML

<input name="name" type="text" size="30" maxlength="50" **IF CHROME == TRUE? document.write("style="position:relative; margin-top:-3px; margin-left:-1px;"");** >

显然,上面的说法是不正确的。。有人能解释一下做这件事的正确方法吗?谢谢

虽然我不喜欢这种一次性的破解,但下面解释了在$.browser.chrome按预期评估的情况下如何获得它。


此时无法将文档写入内联,但是可以更改元素的属性。例如,在条件if检查内部:

$(inputSelector).attr('style',
    'position:relative; margin-top:-3px; margin-left:-1px;');

然而,由于style属性(即"text")被合成为"stye对象",因此通常最好避免文本DOM访问。这可以使用jQuery.css方法实现:

$(inputSelector).css({
    position: 'relative',
    marginTop: '-3px',
    marginLeft: '-1px'
})

其中inputSelector是匹配适当元素的适当选择器。例如,<input name="theName" ..可以与[name="theName"]相匹配。有关更多详细信息,请参阅jQuery选择器。