这是有效的jquery代码吗?

时间:2014-02-08 09:05:23

标签: jquery css width

我的目的是在鼠标悬停时将元素的宽度增加10px,并在鼠标悬停时将其减少10px,这是css中的默认宽度。

根据其他论坛的答案我认为我可以使用:

 $("#theelement").mouseenter(function() {
    $(this).css({"width": $(this.width()+10}) 
  }
 $("#theelement").mousleave(function() {
    $(this).css({"width": $(this.width()-10}) 
  }

事情现在不起作用,我不确定这是否是罪魁祸首。在普通的javascript中我们添加“px”我知道,但不确定。在任何情况下,我都想在不知道静态宽度的情况下动态更改元素的宽度。

4 个答案:

答案 0 :(得分:1)

Use this code: Simple and short!!



$(function(){
    $("#theelement").hover(
        function(){
            $(this).css({"width": $(this).width()+10}); 
        },
        function(){
            $(this).css({"width": $(this).width()-10});
        }
    );                             
});

答案 1 :(得分:0)

您遇到语法错误,您遗失了);对,而$(this.width()需要$(this).width()

 $("#theelement").mouseenter(function () {
    $(this).css({
        "width": $(this).width() + 10
    });
 }); //Here
 $("#theelement").mousleave(function () {
    $(this).css({
        "width": $(this).width() - 10
    })
 }); //And Here

作为旁注:

您只需使用.hover()

即可
 $("#theelement").hover(function () {
    $(this).css({
        "width": $(this).width() + 10
    });
 }, function () {
    $(this).css({
        "width": $(this).width() - 10
    });
 });

答案 2 :(得分:0)

不,$(this.width()应该像这个$(this).width();一样,并且前面的回答者说您在遗漏);时遇到语法错误

$("#theelement").mouseenter(function() {
    $(this).css({"width": $(this).width()+10}) 
  });

 $("#theelement").mousleave(function() {
    $(this).css({"width": $(this).width()-10}) 
  });

答案 3 :(得分:0)

$('#theelement').mouseenter(function () {
    $(this).width(function (index, value) {
        return value + 10;
    });
}).mouseleave(function () {
    $(this).width(function (index, value) {
        return value - 10;
    });
});

这肯定会奏效。看看吧!