如何检测div中鼠标光标的位置[复制]

时间:2022-11-05 07:30:50

This question already has an answer here:

这个问题在这里已有答案:

I have a rectangle span that is 100 pixels wide and I want the user to select from 0-100%.

我有一个100像素宽的矩形跨度,我希望用户从0-100%中选择。

Wherever they click in the div along the width, that is the value that is saved and immediately shown to the user using ajax. So if they click in exactly in the middle of the div, the value saved would be 50%.

无论他们沿着宽度点击div,它都是使用ajax保存并立即显示给用户的值。因此,如果他们完全点击div的中间,保存的值将是50%。

I can't think of an elegant way of doing this! Any tips?

我想不出这样做的优雅方式!有小费吗?

1 个解决方案

#1


4  

Consider using <input type="range"/> in conjunction with <span>

-Edit-

In response to a comment, added fallback support for Firefox via this plugin

在回复评论时,通过此插件添加了对Firefox的后备支持

Updated Demo Fiddle with Polyfill : http://jsfiddle.net/V3ygq/2/

使用Polyfill更新演示小提琴:http://jsfiddle.net/V3ygq/2/

Demo Fiddle: http://jsfiddle.net/V3ygq/

演示小提琴:http://jsfiddle.net/V3ygq/

HTML

Place the range inside of your 100px wide <span>.
<div id="console">...</div>
<span id="container">
     <input id="myRange" type="range" min="0" max="100" />
</span>

jQuery

On change(), do something with the value:
$(function () {
    $("#myRange").on('change', function () {
        // Pull out value, set html of #console DIV
        $("#console").html($(this).val());
    });
    // Set initial value of #console
    $("#myRange").trigger('change');
});

CSS

Hide range selector in <span>, but still allow clicks to change its value
#container {
    width: 100px;
    background: #333;
}
#container input {
    opacity: 0;
}

#1


4  

Consider using <input type="range"/> in conjunction with <span>

-Edit-

In response to a comment, added fallback support for Firefox via this plugin

在回复评论时,通过此插件添加了对Firefox的后备支持

Updated Demo Fiddle with Polyfill : http://jsfiddle.net/V3ygq/2/

使用Polyfill更新演示小提琴:http://jsfiddle.net/V3ygq/2/

Demo Fiddle: http://jsfiddle.net/V3ygq/

演示小提琴:http://jsfiddle.net/V3ygq/

HTML

Place the range inside of your 100px wide <span>.
<div id="console">...</div>
<span id="container">
     <input id="myRange" type="range" min="0" max="100" />
</span>

jQuery

On change(), do something with the value:
$(function () {
    $("#myRange").on('change', function () {
        // Pull out value, set html of #console DIV
        $("#console").html($(this).val());
    });
    // Set initial value of #console
    $("#myRange").trigger('change');
});

CSS

Hide range selector in <span>, but still allow clicks to change its value
#container {
    width: 100px;
    background: #333;
}
#container input {
    opacity: 0;
}