简体   繁体   中英

How to disable Left Click of Mouse for a particluar div using javascript?

I want to disable the left click for a particular div . I have tried the following way but its not working for me:

$('[id$=div]').onclick=function(){xajax_addFunction()};

It is document.ready() . it throws error that xajax_addFunction() is not defined. Please help me. MY code is:

Javascript used for flip:

<script type="text/javascript">

    document.oncontextmenu = new Function("return false")

    var myArray = [];
    var Book_Image_Width = screen.width;
    var Book_Image_Height = screen.height;

    $(document).ready(function (e) {

        var BookId = getParameterByName('BookID');

        ShowImages(BookId);



    });

    function divActive(divId) {
        var div = document.getElementById(divId);
        // div.style.backgroundImage = "url(img/gif/button_add.gif)";
        div.style.cursor = "pointer";
        div.onclick = function () { xajax_addFunction() };
    }

    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regexS = "[\\?&]" + name + "=([^&#]*)";
        var regex = new RegExp(regexS);
        var results = regex.exec(window.location.search);
        if (results == null)
            return "";
        else
            return decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    function ShowImages(QueryString) {
        var Append = '';
        $.ajax({
            type: "POST",
            url: "FlipBook.aspx/Test",
            data: "{QueryString:'" + QueryString + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                ImageBook(data);
            }
        });
    }
    //var firstimg = $('[id$=]')
    $('[id$=divBook]').live('click', function (e) {
        alert('hi');
        e.preventDefault();
        return false;
    });
    // 7 variables to control behavior
    var Book_Image_Width = 324;
    var Book_Image_Height = 500;
    var Book_Border = false;
    var Book_Border_Color = "gray";
    var Book_Speed = 15;
    var Book_NextPage_Delay = 2000;
    var Book_Vertical_Turn = 0;
    var skip = 0;
    var Book_Image_Sources;

    var B_LI, B_MI, B_RI, B_TI, B_Angle = 0, B_CrImg = 6, B_MaxW, B_Direction = 1;
    var B_MSz, B_Stppd = false;
    var B_Permanent_Stppd = false;
    var lastImgIndex = 1;
    var flipStopPoint;

    function ImageBook(data) {

        var test = data.d.split(',').slice(0, -1);
        for (var i = 0; i < test.length; i++) {
            myArray[i] = test[i];
        }
        myArray = test;

        Book_Image_Sources = myArray;
        B_Pre_Img = new Array(Book_Image_Sources.length);

        flipStopPoint = ((Book_Image_Sources.length / 4) - 1) * 50;


        /**Swap Array**/
        for (i = 0; i < Book_Image_Sources.length; i += 2) {
            if (i > 3) {
                if (i != skip) {
                    temp = Book_Image_Sources[i];
                    Book_Image_Sources[i] = Book_Image_Sources[i + 2];
                    Book_Image_Sources[i + 2] = temp;
                    skip = i + 2;
                }
            }
        }

        if (document.getElementById) {
            for (i = 0; i < Book_Image_Sources.length; i += 2) {
                B_Pre_Img[i] = new Image();
                B_Pre_Img[i].src = Book_Image_Sources[i]
            }
            Book_Div = document.getElementById("divBook");
            //Book_Div.removeEventListener('click')
            B_LI = document.createElement("img"); Book_Div.appendChild(B_LI);
            B_RI = document.createElement("img"); Book_Div.appendChild(B_RI);
            B_MI = document.createElement("img"); Book_Div.appendChild(B_MI);
            B_LI.style.position = B_MI.style.position = B_RI.style.position = "absolute";
            B_LI.style.zIndex = B_RI.style.zIndex = 0; B_MI.style.zIndex = 1;
            B_LI.style.top = (Book_Vertical_Turn ? Book_Image_Height + 1 : 0) + "px";
            B_LI.style.left = 0 + "px";
            B_MI.style.top = 0 + "px";
            B_MI.style.left = (Book_Vertical_Turn ? 0 : Book_Image_Width + 1) + "px";
            B_RI.style.top = 0 + "px";
            B_RI.style.left = (Book_Vertical_Turn ? 0 : Book_Image_Width + 1) + "px";
            B_LI.style.height = Book_Image_Height + "px";
            B_MI.style.height = Book_Image_Height + "px";
            B_RI.style.height = Book_Image_Height + "px";
            B_LI.style.width = Book_Image_Width + "px";
            B_MI.style.width = Book_Image_Width + "px";
            B_RI.style.width = Book_Image_Width + "px";
            if (Book_Border) {
                B_LI.style.borderStyle = B_MI.style.borderStyle = B_RI.style.borderStyle = "solid";
                B_LI.style.borderWidth = 1 + "px";
                B_MI.style.borderWidth = 1 + "px";
                B_RI.style.borderWidth = 1 + "px";
                B_LI.style.borderColor = B_MI.style.borderColor = B_RI.style.borderColor = Book_Border_Color
            }

            B_LI.src = B_Pre_Img[0].src;
            B_LI.lnk = Book_Image_Sources[1];
            B_MI.src = B_Pre_Img[2].src;
            B_MI.lnk = Book_Image_Sources[3];
            B_RI.src = B_Pre_Img[4].src;
            B_RI.lnk = Book_Image_Sources[5];
            B_LI.onclick = B_MI.onclick = B_RI.onclick = B_LdLnk;
            //B_LI.onmouseover = B_MI.onmouseover = B_RI.onmouseover = B_Stp;
            //B_LI.onmouseout = B_MI.onmouseout = B_RI.onmouseout = B_Rstrt;
            setTimeout(function () { BookImages(); }, 2000);

        }
    }

    function BookImages() {
        if (!B_Stppd && lastImgIndex < flipStopPoint) {
            lastImgIndex = lastImgIndex + 1;
            if (Book_Vertical_Turn) {
                B_MSz = Math.abs(Math.round(Math.cos(B_Angle) * Book_Image_Height));
                MidOffset = !B_Direction ? Book_Image_Height + 1 : Book_Image_Height - B_MSz;
                B_MI.style.top = MidOffset + "px";
                B_MI.style.height = B_MSz + "px"
            }
            else {
                B_MSz = Math.abs(Math.round(Math.cos(B_Angle) * Book_Image_Width));
                MidOffset = B_Direction ? Book_Image_Width + 1 : Book_Image_Width - B_MSz;
                B_MI.style.left = MidOffset + "px";
                B_MI.style.width = B_MSz + "px"
            }
            B_Angle += Book_Speed / 720 * Math.PI;
            if (B_Angle >= Math.PI / 2 && B_Direction) {
                B_Direction = 0;
                if (B_CrImg == Book_Image_Sources.length) B_CrImg = 0;
                B_MI.src = B_Pre_Img[B_CrImg].src;
                B_MI.lnk = Book_Image_Sources[B_CrImg + 1];
                B_CrImg += 2
            }
            if (B_Angle >= Math.PI) {
                B_Direction = 1;
                B_TI = B_LI;
                B_LI = B_MI;
                B_MI = B_TI;
                if (Book_Vertical_Turn) B_MI.style.top = 0 + "px";
                else B_MI.style.left = Book_Image_Width + 1 + "px";
                B_MI.src = B_RI.src;
                B_MI.lnk = B_RI.lnk;

                setTimeout("Book_Next_Delay()", Book_NextPage_Delay)
            }
            else setTimeout("BookImages()", 50)
        }
        else setTimeout("BookImages()", 50)
    }

    function Book_Next_Delay() {
        if (B_CrImg == Book_Image_Sources.length) B_CrImg = 0;
        B_RI.src = B_Pre_Img[B_CrImg].src;
        B_RI.lnk = Book_Image_Sources[B_CrImg + 1];
        B_MI.style.zIndex = 2;
        B_LI.style.zIndex = 1;
        B_Angle = 0;
        B_CrImg += 2;
        setTimeout("BookImages()", 50)
    }



    function B_LdLnk() { if (this.lnk) window.location.href = this.lnk }
    function B_Stp() { B_Stppd = true; this.style.cursor = this.lnk ? "pointer" : "default" }
    function B_Rstrt() { B_Stppd = false }
</script>

HTML code is:

<div id="divBook" style="position: relative">
    <input type="hidden" runat="server" id="htmlHiddenImageOrder" />
</div>

I am binding the images dynamically.

Try this,

(function($){
  $(document).ready(function () {
     $("#divBook")
     .mousedown(function (event) {
        var clickVar = (navigator.appName == "Netscape" || navigator.appName == "Opera") ? 0 : 1;
        if (event.button == clickVar) {                
            event.preventDefault();
            $(this).unbind('click');
        }
    });
 });

})(jQuery);

Here, this should be a little simpler:

<style type='text/css'>
#innerDiv {
    display:inline-block;
    background-color: #999;
}

#outerDiv {
    background-color: #444;
}
</style>

<div id='outerDiv'>
    outerDiv: click works here
    <div id='innerDiv'>innerDiv: click doesn't work here</div><br />
    outerDiv: click works here</div>


<script type='text/javascript'> 

$(function () {  //short hand for window.onLoad or $(document).ready()
    $('#outerDiv').on('mousedown', function (event) {
        alert('outerDiv: mousebutton fired');
    });

    $('#innerDiv').on('mousedown', function (event) {
       // all browsers except IE before version 9        // Internet Explorer before version 9
       if ((('which' in event) && (event.which == 1)) || (('button' in event) && (event.button == 1))) {
           alert ('innerDiv: Left button is pressed inside');
           return false; //prevent bubbling and default action
       } else {
           alert('innerDiv: NOT-LEFT button is pressed inside');   
       }
    });
});

</script>

If the left button is clicked in the inner div, the inner div left button message will fire and the event will stop from bubbling up. If the right button is pressed inside the inner div the 'NOT-LEFT' alert message will fire and the event will bubble up.

I have chosen return false; to prevent the default action and stop the event from bubbling up.

First, I would like to direct you to reading this page from Dottoro Web Reference on mouse events so you can understand the event object and why I used both event.button and event.which.

Next, here is a page that describes the order of events when a mouse is clicked. Also from Dottoro Web Reference. You can see that the event in cancelable and it does bubble up to parent nodes.

Lastly I would like to let you know the difference between return false , event.preventDefault() , event.stopImmediatePropagation() , and event.stopPropagation() so I would direct you to here to find out the differences.

Cheers and good reading.

A few notes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM