how to make div click-able?

2020-02-08 05:32发布

<div><span>shanghai</span><span>male</span></div>

For div like above,when mouse on,it should become cursor:pointer,and when clicked,fire a

javascript function,how to do that job?

EDIT: and how to change the background color of div when mouse is on?

EDIT AGAIN:how to make the first span's width=120px?Seems not working in firefox

9条回答
贪生不怕死
2楼-- · 2020-02-08 06:05

I suggest to use jQuery:

$('#mydiv')
  .css('cursor', 'pointer')
  .click(
    function(){
     alert('Click event is fired');
    }
  )
  .hover(
    function(){
      $(this).css('background', '#ff00ff');
    },
    function(){
      $(this).css('background', '');
    }
  );
查看更多
你好瞎i
3楼-- · 2020-02-08 06:06

<div style="cursor: pointer;" onclick="theFunction()">

is the simplest thing that works.

Of course in the final solution you should separate the markup from styling (css) and behavior (javascript) - read on it on a list apart for good practices on not just solving this particular problem but in markup design in general.

查看更多
地球回转人心会变
4楼-- · 2020-02-08 06:06

add the onclick attribute

<div onclick="myFunction( event );"><span>shanghai</span><span>male</span></div>

To get the cursor to change use css's cursor rule.

div[onclick] {
  cursor: pointer;
}

The selector uses an attribute selector which does not work in some versions of IE. If you want to support those versions, add a class to your div.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-02-08 06:15

The simplest of them all:

<div onclick="location.href='where.you.want.to.go'" style="cursor:pointer"></div>
查看更多
神经病院院长
6楼-- · 2020-02-08 06:16

Give it an ID like "something", then:

var something = document.getElementById('something');

something.style.cursor = 'pointer';
something.onclick = function() {
    // do something...
};

Changing the background color (as per your updated question):

something.onmouseover = function() {
    this.style.backgroundColor = 'red';
};
something.onmouseout = function() {
    this.style.backgroundColor = '';
};
查看更多
Deceive 欺骗
7楼-- · 2020-02-08 06:18

If this div is a function I suggest use cursor:pointer in your style like style="cursor:pointer" and can use onclick function.

like this

<div onclick="myfunction()" style="cursor:pointer"></div>

but I suggest you use a JS framework like jquery or extjs

查看更多
登录 后发表回答