开发者

One Input - two styles? Left side cursor:text, right side cursor:pointer?

Is there a way (using javascript/jQuery) to do following:

On my page, I have one input type=text. This input has a background-image on its right side.

<input id="my-input" type="text" value="foobar" style="background-image:url(path/to/my/image.gif); background-position:right center; background-repeat:no-repeat; height:17px; width:97px;"/>

When the cursor moves over the background-image (width:21px), the cursor icon should be set to pointer. Otherwise it should be cursor:text.

I have to use the input! I am not able to create a new div next to the input for this icon!

I tried to solve this problem like this:

$('#my-input').mousemove(function (event) {
    this.style.cursor = ((event.offsetX || event.layerX) < this.offsetWidth - 21) ? "text" : "pointer";
});

But this won't work. this.offsetWi开发者_StackOverflow社区dth - 21 has the right value but event.layerX and event.offsetX is undefined.

Do you have another idea, how to solve this problem? Can you tell me, why my js won't work as I want it to do?


I tried this way and its working (tested on IE). Check out here.

$('#my-input').mousemove(function (event) { 

  $(this).css("cursor", ((event.offsetX || event.layerX) < this.offsetWidth - 21) ? "text" : "pointer");

 }); 


Mouse position is one of those problems I always look up. Here is one solution. Notice in particular that halfway down is a snippet that shows how to determine the mouse position relative to the upper left corner of the object in question (e.g. a text field). That may be relevant to solving your problem.

Maybe something like the following would work

$('#my-input').mousemove(function(e) {
    var pos = e.pageX - this.offsetLeft;
    this.style.cursor = (pos < this.offsetWidth - 21) ? 'text' : 'pointer';
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜