0

我有一个简单的表格,必须可以访问。如果有人错过了必填字段,错误应该显示在我放置 div 标签的页面顶部。现在,当我单击提交按钮后,它应该在页面顶部显示一条错误消息,然后具有焦点,以便屏幕阅读器可以阅读它而无需刷新页面。我只是无法专注于那个错误。任何建议将不胜感激。谢谢我的代码看起来像这样

<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script>
function myFunction() {
    document.getElementById("errors").innerHTML = "ERROR ON THE FORM";
}

function getfocus() {
    document.getElementById("errors").focus();
}

function printnfocus() {
    if (myFunction()) {
        getfocus();
    }
}
</script>
</head>

<body>
    <div id="errors"></div>
    <fieldset>
        <legend>Eligibility</legend> <input type="checkbox" id="citizen"> <label for="citizen">I am a U.S. citizen</label><br>
        <input type="checkbox" id="18"> <label for="18">I am a 18 years old</label>
    </fieldset>
    <p>
        <br>
    </p>
    <form id="sex" name="sex">
        <fieldset>
            <legend>Sex:</legend> <label for="male">Male</label> <input type="radio" name="sex" id="male" value="male"><br>
            <label for="female">Female</label> <input type="radio" name="sex" id="female" value="female"><br>
            <br>
        </fieldset>
    </form>
    <fieldset>
        <legend>Personal Information</legend>
        <form>
            <label for="lname">Last Name</label> <span title="lblAstrisk" class="asterisk" style="color:red">*</span> <input type="text" name="lname" id="lname" required=""><br>
            <br>
        </form>
    </fieldset>
    <p>
        <button type="button" onclick="printnfocus()">Submit</button>
    </p>
</body>
</html>
4

1 回答 1

2

您正在寻找window.scrollTo(). 您可以通过以下方式获取errorsdiv 的位置:

document.getElementById('errors').offsetTop
于 2013-08-13T22:05:46.823 回答