使用 javascript 访问 `draggable` 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15806679/
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-27 02:09:57  来源:igfitidea点击:

Access the `draggable` attribute with javascript

javascripthtmldraggable

提问by Tbi45

So the question is : How can you do that ? I want to change the draggableattribute to "false"so the element that was previously draggable will lose this property.

所以问题是:你怎么能做到这一点?我想将draggable属性更改为,"false"以便以前可拖动的元素将丢失此属性。

I will give you a div so you will have something to start with :

我会给你一个div,这样你就可以开始了:

     <div id="div1"  draggable="true" ondragstart="drag(event) "onDblClick="edit('div1')">
     </div>

回答by

document.getElementById('div1').setAttribute('draggable', false);

OR

或者

var elem = document.getElementById('div1');
elem.setAttribute('draggable', false);

If you want the attribute totally gone use;

如果您希望该属性完全消失,请使用;

elem.removeAttribute('dragable');

回答by Kovge

There is many ways, if you use jQuery:

有很多方法,如果你使用jQuery

    $('#div1').attr('dragabble'); //returns with the value of attribute
    $('#div1').attr('dragabble','false'); //sets the attribute to false

Native JS:

原生JS:

    document.getElementById('div1').getAttribute('draggable'); //returns the value of attr
    document.getElementById('div1').setAttribute('draggable', 'false'); //set the value of attr

回答by Surya Deepak

You might want to use jquery-ui draggable component to acheive ur required functionality.. or if u have jquery library in ur Dev environment u can use the following code

您可能想使用 jquery-ui 可拖动组件来实现您所需的功能.. 或者如果您的开发环境中有 jquery 库,您可以使用以下代码

$("#div1").attr('draggable',false);

$("#div1").attr('draggable',false);

or using javascript we can do it as follows

或使用 javascript 我们可以按如下方式进行

document.getElementById('div1').setAttribute('draggable', 'false');

document.getElementById('div1').setAttribute('draggable', 'false');

回答by Jingshao Chen

After set the attribute draggableto true, you mostly often want to handle dragstartevent. To do that in native JS:

将属性设置draggable为 后true,您通常希望处理dragstart事件。要在本机 JS 中做到这一点:

elem.addEventListener('dragstart', ev => {
  // dragstart handlings here
  }, false)

回答by Ryan Dunphy

I'm a little late to the party, but is there a reason why we wouldn't just want to write something like this?

我参加聚会有点晚了,但是我们有什么理由不想写这样的东西吗?

var el = document.createElement('div');
el.draggable = false;

Seems to apply the attribute fine for me.

似乎对我来说很好地应用了该属性。