使用 Javascript/JQuery 在网页上将 div 移动到另一个上方?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13907168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:08:22  来源:igfitidea点击:

Moving div above another on a web page using Javascript/JQuery?

javascriptjquerygoogle-chromehtml

提问by whitfin

I've seen a lot about doing this in CSS (far from ideal), but I'm thinking of building a Chrome extension and it requires that a div is inserted prior to another (for clarification, I mean that when testing the extension I need to drag the div above the other using Chrome Dev Tools). Is there a way to do this upon page load using Javascript/JQuery (or some other way which can be done via Chrome Extension)?

我已经看到很多关于在 CSS 中执行此操作(远非理想),但我正在考虑构建一个 Chrome 扩展程序,它需要在另一个之前插入一个 div(为了澄清,我的意思是在测试扩展程序时我需要使用 Chrome 开发工具将 div 拖到另一个上方)。有没有办法在页面加载时使用 Javascript/JQuery(或其他一些可以通过 Chrome 扩展程序完成的方式)来做到这一点?

In previous attempts I've tried using insertAfter()/insertBefore()and before()and had no luck (although I might be missing something obvious), so I guess another question is do these need to be used in a certain way within a Chrome Extension?

在之前的尝试中,我尝试使用insertAfter()/insertBefore()并且before()没有运气(尽管我可能会遗漏一些明显的东西),所以我想另一个问题是这些是否需要在 Chrome 扩展程序中以某种方式使用?

Thanks in advance for any help!

在此先感谢您的帮助!

回答by Purag

Hereis a little demonstration.

是一个小演示。

The insertBeforecode being used is this:

insertBefore正在使用的代码是这样的:

$("<div>").prop("id","between").insertBefore("#blah");

The first two jQuery functions just create the divelement. If you want to move an existing one:

前两个 jQuery 函数只是创建div元素。如果要移动现有的:

$("#existingDiv").insertBefore("#otherDiv");

And this should be pretty self-explanatory.

这应该是不言自明的。

For plugins, load jQuery asynchronously. Something like this should do:

对于插件,异步加载 jQuery。这样的事情应该做:

(function(){
    var s = document.createElement('script');
    s.src = 'http://code.jquery.com/jquery-1.8.2.min.js';
    document.getElementsByTagName('head')[0].appendChild( s );
})();

回答by BBagi

jQuery has a very easy method to move one node before another, which you touched upon in your question:

jQuery 有一种非常简单的方法可以将一个节点移动到另一个节点之前,您在问题中提到了这一点:

BEFORE:

前:

<div id="first"></div> <div id="second"></div>

<div id="first"></div> <div id="second"></div>

$("#second").insertBefore("#first");

AFTER:

后:

<div id="second"></div> <div id="first"></div>

<div id="second"></div> <div id="first"></div>



As far as Chrome, you may want to do some digging to see if jQuery is loaded by the time you make your call or not

就 Chrome 而言,您可能需要进行一些挖掘,以查看在您拨打电话时是否已加载 jQuery