开发者

using access key for browser to underline the first character of all links with access keys

开发者 https://www.devze.com 2023-01-13 20:40 出处:网络
I am trying to figure out how to use the dom to access the access keys of each access keyed li开发者_StackOverflow中文版nk and underline the first character of all of the links on the page when the ac

I am trying to figure out how to use the dom to access the access keys of each access keyed li开发者_StackOverflow中文版nk and underline the first character of all of the links on the page when the access key is pressed.

i.e. when the person presses alt in IE and Chrome all of the first letters of the links underline letting the person know which key to press. Also is there anyway to do it by creating a universal [access key] for all browsers using javascript or are you forced to use the multiple methods for each browser and thus stuck writing a class for each browser?

I found one way using a <span> around the character, but that just doesn't seem like good practice and it would be nice if the dom would just grab the access key and underline the letter in the link and modify it with an underline.

Any help is greatly appreciated.


var labels= document.getElementsByTagName('label');
for (var i= labels.length; i-->0;) {
    var label= labels[i];
    if (!label.htmlFor) continue;
    var field= document.getElementById(label.htmlFor);
    if (!field) continue;
    if (!field.accessKey) continue;
    var ix= label.firstChild.data.toLowerCase().indexOf(field.accessKey.toLowerCase());
    if (ix===-1) continue;
    var next= label.firstChild.splitText(ix+1);
    var span= document.createElement('span');
    span.className= 'accesshighlight';
    span.appendChild(label.firstChild.splitText(ix));
    label.insertBefore(span, next);
}

This will wrap a <span class="accesshighlight"> around the first matching letter in a label, assuming that labels contain text content and not more elements (if you need to look for matching text in subelements that's a bit more time-consuming). Then you can say:

body.showhighlights .accesshighlight {
    text-decoration: underline;
}

and toggle the presence of class="showhighlights" on document.body when alt is pressed.

0

精彩评论

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