在单击按钮时停止背景可拖动

时间:2017-11-17 09:00:13

标签: jquery

我有一些代码,当我按下按钮时,div中的背景开始可以拖动。我想做点什么,比如当我点击其他按钮后,后台停止可拖动,再次按下按钮,bg开始再拖动。

<html>
<script type="text/javascript" 
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
<script src="draggable_background.js"></script>

<style>     
div { width: 320px; height: 240px; display: inline-block; font-family: 
sans-serif; border: 2px solid #aaa;}
</style>

<body>
<div id="default" style="background:url('aaa.jpg')">default</div>

<br><br>
<button id="first"></button>


<script>
$(document).ready(function(){
$('#first').click(function() {
  $('#default').backgroundDraggable();
  $('div').each(function() {
    var $this = $(this),
        html = $this.html();
    $this.empty().append($('<p>').html(html))
  });
  });
});

</body>
</html>

2 个答案:

答案 0 :(得分:0)

试试这个 <button id="second">Second</div> 在jQuery中

<script>
 $('#second').on('click',function(){
    $('#default').backgroundDraggable('destroy');
  });

 </script>

答案 1 :(得分:0)

我相信你正在使用这个库https://github.com/kentor/jquery-draggable-background

要禁用可拖动功能,您可以调用

$('div').backgroundDraggable('disable');

要使按钮切换isDraggable,可以使用变量isDraggable,并检查是否切换拖动或禁用拖动

这里是完整的例子

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="draggable_background.js"></script>
</head>


<style>     
div { width: 320px; height: 240px; display: inline-block; font-family: 
sans-serif; border: 2px solid #aaa;}
</style>

<body>
    <div id="default" style="background:url('bg.jpg')">default</div>

    <br><br>
    <button id="first">DRAG</button>


    <script>
    //While in global context declare variable
    var isDraggable = false;

    $(document).ready(function(){
        $('#first').click(function() {

            if (!isDraggable)
            {
                //Not Draggable, then make it draggable
                $('#default').backgroundDraggable();
                $('div').each(function() {
                    var $this = $(this);
                    var html = $this.html();
                    $this.empty().append($('<p>').html($this.html()));
                });
                isDraggable = true;
            } else
            {
                //Already draggable, then disable it
                $('#default').backgroundDraggable('disable');
                isDraggable = false;
            }

        });
    });
    </script>
</body>
</html>