如何检测是否单击了$(this)元素以外的鼠标

时间:2015-08-29 08:34:00

标签: javascript jquery html css

如果在元素中单击鼠标(此处为.block),我想应用一些样式。如果单击该元素,则按$(this)获取该元素并设置其样式。此后,当用户点击$(this)元素以外的其他元素时,我想将其更改回默认样式。如何检测是否单击了$(this)元素以外的鼠标。

到目前为止

js脚本:

$( document ).ready(function() {

    // when a block is clicked get that specific block
    $('.block').click(function() {
        var block = $(this);
        block.css('background','red');
    });

    //if clicked other than the block do stuff

});

jsfiddle

7 个答案:

答案 0 :(得分:14)

更好的方法是使用:focus和css .container{ border:1px solid #333; width:200px; height:200px; } .block{ background-color: #ccc; width:50px; float:left; height:50px; margin:20px; } .block:focus{ background-color: red; outline:none }选择器



<div class="container">
  <div class="block" id="block1" tabindex="1">
    </div>
  <div class="block" id="block2" tabindex="1">
    </div>
  <div class="block" id="block3" tabindex="1">
    </div>
  <div class="block" id="block4" tabindex="1">
    </div>
</div>
&#13;
{{1}}
&#13;
&#13;
&#13;

答案 1 :(得分:5)

您可以尝试这样的事情: -

$(document).ready(function () {

    // when a block is clicked get that specific block
    $('.block').click(function () {
        var block = $(this);
        block.css('background', 'red');
    });

    //if clicked other than the block do stuff
    $('html:not(.block)').click(function () {
        //your logic here
    });
});

FIDDLE DEMO

答案 2 :(得分:3)

您可以绑定body上的点击事件,并使用#a函数检查是否点击了e.target

&#13;
&#13;
$('div').click(function () {
    $(this).css('background', 'red')
})
$('body').click(function (e) {
    if ($(e.target).is($("#a"))) {
        
    } else {
        $('#a').css('background','tomato')
    }
})
&#13;
div {
    width:100px;
    height:100px;
    background:tomato;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="a"></div>
&#13;
&#13;
&#13;

答案 3 :(得分:2)

添加一个CSS类,表示当前所选块的样式和选定状态:

public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub

        ViewHolder holder = null;

        if (convertView == null)
        {
            LayoutInflater inflater = context.getLayoutInflater();
            convertView = inflater.inflate(R.layout.new_list_clinics, null);
            holder = new ViewHolder(convertView);

            convertView.setTag(holder);


        }
        else
        {
            holder = (ViewHolder)convertView.getTag();
        }

        final String telePhoneNumber = "tel:"+list.get(position).getTelephoneNumber();
        final String latitude = list.get(position).getLatitude();
        final String longitude = list.get(position).getLongitude();
        final String clinicName = list.get(position).getClinicName();
        holder.tvAddress.setText(list.get(position).getAddress());
        holder.tvClinicName.setText(clinicName);

        List<ModelClinicList> opList = list.get(position).operatingHoursList;

        for (int i = 0; i < opList.size(); i++){
            TableRow tableRows = new TableRow(context);
            tableRows.setLayoutParams(params);
            TextView tvLabel = new TextView(context);

            tvLabel.setLayoutParams(tvParams);

            tvLabel.setText(opList.get(i).dayName);

            holder.ll.addView(tvLabel);
        }

        return convertView;
    }

在单击处理程序中,从所选的块中删除该类。 (如果未选择任何块,.block.selected { background: red; } 将不执行任何操作。)然后将该类添加到新单击的块中:

removeClass()

Fiddle 1

<小时/> 的更新

  

如何知道是否在块内或其他.block

中单击了它

使用hasClass()确定您是否点击了同一个区块两次:

$('.block').click(function() {
  $('.block.selected').removeClass('selected');
  $(this).addClass('selected');
});

Fiddle 2

答案 4 :(得分:1)

在JS中执行此操作将类似于

&#13;
&#13;
var globalRef;
var inside = document.querySelectorAll('.inside');

document.querySelector('.block').addEventListener('click', function (e) {

    if (globalRef != undefined) {
        globalRef.style.background = 'none'
    }

    globalRef = e.target;
    e.target.style.background = 'red'
}, false);
&#13;
.block {
    width:200px;
    height:200px;
    background:#ccc;
}
.inside {
    display:inline-block;
    width:100px;
    height:100px;
    border:1px solid green;
    box-sizing:border-box;
    float:left
}
&#13;
<div class="block">
    <div class='inside'></div>
    <div class='inside'></div>
    <div class='inside'></div>
    <div class='inside'></div>
</div>
&#13;
&#13;
&#13;

答案 5 :(得分:1)

请参阅下面的工作示例代码中的注释。

<!doctype html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
        <style>
            .block {
                background: gray;
                width: 100px;
                height: 100px;
                float: left;
                margin-left: 20px;
            }
        </style>
    </head>
    <body>
        <div class="block" id="block1"></div>
        <div class="block" id="block2"></div>
        <div class="block" id="block3"></div>
        <script type="text/javascript">
            $(document).ready(function() {
                /*
                Solution 1:
                This gathers all elements with the class 'block' and defines a click event on it.
                In the click event all elements with class 'block' are walked through. If an element
                has the same id as the current element's id, than do one thing else do another thing.
                In this example background color en content of the three divs are changed
                */
                $('.block').click(function(i) {
                    /*
                    Notice the usage of $(this) and this in the code below. $(this) Is the
                    jquery element while 'this' is the DOM element.
                    */
                    var block = $(this);
                    $(".block").each(function(){
                        if (this.id == block.attr("id")) {
                            this.innerHTML = ("My id is " + this.id);
                            this.style.background = "red";
                        } else {
                            this.innerHTML = "";
                            this.style.background = "gray";
                        }
                    })
                });
                /*
                Solution 2:
                For each element you want actions on, define a separate click event.
                */
                $('#block1').click(function(i) {
                  alert("You clicked me?");
                });
                $('#block2').click(function(i) {
                  alert("Why did you click me?");
                });
                $('#block3').click(function(i) {
                  alert("Hi there, what's new?");
                });
            });
        </script>
    </body>
</html>

答案 6 :(得分:1)

根据Akshay的回答:

$('body').click(function (e) {
    var clicked = $(e.target);

    //See if the clicked element is (or is inside) a .block:
    var clickedBlock = clicked.closest('.block');
    if (clickedBlock.length) {
        clickedBlock.css('background', 'red');
    }

    //Remove the overridden background from other blocks:
    var allBlocks = $('.block');
    allBlocks.not(clickedBlock).css('background', '');
});

JSFiddle:http://jsfiddle.net/ftq8a6ex/5/