简体   繁体   中英

jQuery - Cant use clientX to change a css attribute

Here is my problem

I want to move a div from its position to the mouses position when i mouseover an element.

Almost like a "tooltip", but when i mouseover it doesnt move. Here is the code:

$item.mouseover(function (){

//make visible
   $tooltip.show();

    //change left and top values to mouse values
   $tooltip.css("left","event.clientX + 'px'");
   $tooltip.css("top","200px");         
 });

The "event.clientX + 'px'" doesn't seem to work, is there anyway i can get this to work? The top attribute is changed without problems but I cant get the mouse value to work.

how can i change the item.left & .top values to that of the mouses?

ty in advance!

-Thaiscorpion

edit: Wow thats for the really super fast answers im gonna trythem right now thanx!!

You're setting the css property to event.clientXpx literally. Put event.clientX outside the quotes:

 $tooltip.css("left", event.clientX + "px");

Here is a redone version of your code: http://jsfiddle.net/maniator/EzdBx/

var $tooltip = $('#tooltip')

$('.hover').hover(function(event) {
    //make visible
    $tooltip.show();
    //change left and top values to mouse values
    $(this).bind('mousemove', function(event) {
        $tooltip.css("left", event.clientX);
        $tooltip.css("top", event.clientY);
    })
}, function() {
    $tooltip.hide();
});

css:

#tooltip {
    display: none;
    position: absolute;
    /* anything you want here and below */
    width: 50px;
    background: blue;
}

replace:

$item.mouseover(function (){

  //make visible
  $tooltip.show();

  //change left and top values to mouse values
  $tooltip.css("left","event.clientX + 'px'");
  $tooltip.css("top","200px");         
});

with:

$item.mouseover(function (){

//make visible
$tooltip.show();

 //change left and top values to mouse values
 $tooltip.css("left",event.clientX + 'px');
 $tooltip.css("top","200px");         
 });

You're treating the event object as a string. So your call to $.css() would be more like this:

$item.mouseenter(function(event){
  $tooltip
    .show()
    .css({
      left: event.clientX + "px",
      top: '200px'
  }); 
});

Demo: http://jsbin.com/uzicek/5/edit

您需要更改其position属性,可能还要更改z-index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM