开发者

Checking input elements on Firefox with JavaScript

开发者 https://www.devze.com 2022-12-12 22:33 出处:网络
I\'m developing an extension, which listens to click events on elements. Now I have two questions: Is there a convenient way to detect whether an element is an input element? Like input, textarea i

I'm developing an extension, which listens to click events on elements.

Now I have two questions:

  1. Is there a convenient way to detect whether an element is an input element? Like input, textarea in HTML, and textbox in XUL.
  2. If the user clicked on an input element, how to get the position where the user clicked? For example, there's an <input> element, with its value set to blah, and the user clicked between 'l' and 'a', how can I get the index(开发者_运维问答in this case it's 2)?


Every event has some data that gets passed with it in the event param. You can do something like this to figure out what was clicked on:

function clickFun(event){
    if (event.target.nodeName == "INPUT") {
        var type = event.target.getAttribute('type').toLowerCase();
        if (type == 'text') {
            console.log('text input');
        } else if (type == 'checkbox') {
            console.log('checkbox');
        }
    } else if (event.target.nodeName == "TEXTAREA") {
        console.log('text area');
    }
}
thing.onclick = clickFun;

You can do this with jQuery which gives you some easy functions to check out information about elements. Up to you if you want to try out a javascript framework.

$(':input').click(function(event){
    var $this = $(this);
    if ($this.is(':text')) {
        console.log('text input');
    } else if ($this.is(':checkbox')) {
        console.log('checkbox');
    } else if ($this.is(':textarea')) {
        console.log('textarea');
    }
});

To get the position of the cursor when they click in a text box or area try checking out this article:

http://www.dedestruct.com/2008/03/22/howto-cross-browser-cursor-position-in-textareas/


For #1: it's convenient to use the jQuery ":input" selector like this:

if ($(node).is(":input"))
    alert("It's an input element!");

But generally, I don't think there is an easy way to tell XUL elements. Enumerating node names would be the simplest solution I could think of.

0

精彩评论

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