如何关注页面顶部的文本

How to focus on the text in top of page

本文关键字:文本 顶部 何关注      更新时间:2023-09-26

我有一个简单的表单,它必须是可访问的。如果有人遗漏了一个必填字段,则错误应该显示在我放置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>

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

document.getElementById('errors').offsetTop