最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I prevent drag and drop images in a react app? - Stack Overflow

programmeradmin2浏览0评论

We got how to prevent drag drop image with jquery with $('img').on('dragstart', function(event) { event.preventDefault(); }); but I want to achieve the same in a react app, and without jquery. How can I do this ? a) locally (image per image) b) globally (for all images of the react app)

I still want to keep control over other interactions, so img { pointer-events: none; } is not a solution.

The goal is to prevent saving image through drag and drop.

We got how to prevent drag drop image with jquery with $('img').on('dragstart', function(event) { event.preventDefault(); }); but I want to achieve the same in a react app, and without jquery. How can I do this ? a) locally (image per image) b) globally (for all images of the react app)

I still want to keep control over other interactions, so img { pointer-events: none; } is not a solution.

The goal is to prevent saving image through drag and drop.

Share Improve this question asked Apr 18, 2018 at 11:37 SoleilSoleil 7,2876 gold badges45 silver badges71 bronze badges 3
  • @ArmanCharan Yes, it (draggable="false") works for images for which onClick={} is doing something, but for the others, it works when I do this directly, but when I click once, the image is kind of selected and then I can drag it for unknown reason. – Soleil Commented Apr 18, 2018 at 11:47
  • As @ArmanCharan mentioned, adding a draggable attribute works as you can see for yourself here: codesandbox.io/s/4r6p4jyko4 But it'll be really helpful if you could show us what you have tried till now. Apologies if I misunderstood the question. – Shishir Anshuman Commented Apr 18, 2018 at 11:49
  • @ShishirAnshuman As I commented, I see the same specific problem with your quoted example. – Soleil Commented Apr 18, 2018 at 12:01
Add a comment  | 

2 Answers 2

Reset to default 18

You can use onDragStart:

onDragStart={this.preventDragHandler}

And the handler:

preventDragHandler = (e) => {
  e.preventDefault();
}

For apps using HTML5, setting draggable={false} in react should accomplish this as well. It will wind up setting the HTML5 draggable attribute to "false".

Another option would be to just use CSS and set pointer-events: none; on the image.

发布评论

评论列表(0)

  1. 暂无评论