开发者

<Control>.Focus() from server side doesn't scroll into view

Custom Validation Control:

<asp:CustomValidator
ID="valSex" runat="server" ErrorMessage="1.2 &lt;b&gt;Sex&lt;/b&gt; not specified"
EnableClientScript="true" ClientValidationFunction="ValidateSex" SetFocusOnError="True">Selecti开发者_如何转开发on required</asp:CustomValidator>

Client Side validation routine:

function ValidateSex(source, args) {

    var optMale = document.getElementById("<%=optMale.ClientID %>");
    var optFemale = document.getElementById("<%=optFemale.ClientID %>");

    if (!optMale.checked && !optFemale.checked) {
        args.IsValid = false;
        optMale.focus();
    }
    else
        args.IsValid = true;
}

When the page is submitted and Sex is not specified, focus is set but the 2 radio buttons are not quite in view, vertical scrolling is required to bring them into view.

Shouldn't the Focus() method have brought the focus control into view?


I don't think all browsers necessarily implement it that way. You can scroll it into view using scrollTo(x, y).

The following should do the trick:

function scrollToElement(elementId)
    var offset = findPos(document.getElementById(elementId));
    var x = offset[0];
    var y = offset[1];

    window.scrollTo(x, y);
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);// yes, it's an assignment
    }
    return [curleft,curtop];
}

More on finding position at http://www.quirksmode.org/js/findpos.html.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜