Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在图元处单击“插入顶部”_Javascript_Jquery - Fatal编程技术网

Javascript 在图元处单击“插入顶部”

Javascript 在图元处单击“插入顶部”,javascript,jquery,Javascript,Jquery,我想在单击链接时添加顶部元素 我尝试在js上执行此操作,但不起作用: $(function test() { var newtop = $('.plugin-noticias').position().top + 100; $('.plugin-noticias').css('top', newtop + 'px'); }); 在链接上显示: <a href="#" onclick="test()"><img src="img/seta-cima.png" alt=

我想在单击链接时添加顶部元素

我尝试在js上执行此操作,但不起作用:

$(function test() {     
var newtop = $('.plugin-noticias').position().top + 100;
$('.plugin-noticias').css('top', newtop + 'px');
});
在链接上显示:

<a href="#" onclick="test()"><img src="img/seta-cima.png" alt="Setas" /></a>


为什么不起作用?

您正在使用联机函数调用。必须在浏览器到达
onclick=
行之前声明函数


从DOM ready中展开函数并将其放在头部。

如果要从onclick属性调用函数(最好在jquery imo中绑定它),则应该这样声明它,以便它位于正确的范围内:

function test() {     
    var newtop = $('.plugin-noticias').position().top + 100;
    $('.plugin-noticias').css('top', newtop + 'px');
}
我实际上要做的是:

<a href="#" id="test"><img src="img/seta-cima.png" alt="Setas" /></a>

$(function() {
    // bind the click event using jquery
    $('#test').on('click', function(e) {
        e.preventDefault(); // stop the link click 
        var newtop = $('.plugin-noticias').position().top + 100;
        $('.plugin-noticias').css('top', newtop + 'px');
    }
});

$(函数(){
//使用jquery绑定click事件
$('#test')。在('click',函数(e)上{
e、 preventDefault();//停止链接并单击
var newtop=$('.plugin noticeas').position().top+100;
$('.pluginnoticeas').css('top',newtop+'px');
}
});

您可以使用jquery将100px添加到顶部,而不必自己计算

function test(){
    $(".plugin-noticias").css({
        top: "+=100px" 
    });
}

另外,您的代码有语法错误。您不必将每个函数都包装到jquery函数中。

我认为您需要的是:

$(function() { 
    window.test = function(){    
        var newtop = $('.plugin-noticias').position().top + 100;
        $('.plugin-noticias').css('top', newtop + 'px');
    }
});