使用JavaScript更改输入边框颜色无效

Changing Input Border Colour with JavaScript not working

本文关键字:边框 颜色 无效 输入 JavaScript 使用      更新时间:2023-09-26

我读了一些关于SO的问题,我相信我做的是正确的,但它仍然不起作用!

我使用的是普通的旧JavaScript,因为它是遗留代码,但如果必须的话,我可能也可以使用jQuery。

我有我的表格,它是这样的(无意双关):

<form action="submit.php" method="post" name="myForm" onsubmit="return validateInfoForm()">
    <input type="text" class="boxes" name="Forename" id="Forename" placeholder="Forename" />
    ....
</form>

JS

function validateInfoForm()
{
    var b=document.forms["myForm"]["Forename"].value;
    var c=document.forms["myForm"]["Surname"].value;
    var f=document.forms["myForm"]["Postcode"].value;
    var g=document.forms["myForm"]["Telno"].value;
    var h=document.forms["myForm"]["Email"].value;
    if (b==null || b=="")
{
    alert("Enter Forename");
    document.getElementById('Forename').style.borderColor = "#FF0000";
   // before it was using document.forms["myForm"]["Forename"] as the selector but I changed it to try and get it to work. It was also doing .focus() rather than changing the border colour.
    return false;
}

在没有收到任何错误的情况下,我只是得到了警告框,然后我的光标被放置在输入中,这也是我不想要的,因为它正在删除占位符,这就是为什么我删除了.focus()并试图更改颜色。

有什么想法吗?

我猜它正在更改边框颜色,但因为元素没有边框,所以没有应用它尝试:

 document.getElementById('Forename').style.border = "1px solid #ff0000";

也可以尝试设置边框宽度和样式。

我遇到了同样的问题,经过多次搜索,我找到了这个解决方案,试试…

// Create our shared stylesheet:
const sheet = new CSSStyleSheet();
sheet.replaceSync('#target {color: darkseagreen}');
// Apply the stylesheet to a document:
document.adoptedStyleSheets = [sheet];

它对我有效。