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

javascript - How to reverse onClick event? - Stack Overflow

programmeradmin1浏览0评论

I wanted to add inner shadow to a search box when the user clicks on it so I used this simple code :

function shadow()
{
document.getElementById("search2").style.boxShadow="inset 0px 0px 12px 0px rgba(0,0,0,0.75)";
}

And the markup :

<input type="search" onClick="shadow()"> 

So that when you click on the search box, the "search2" div gets an inner shadow and it works. But I want to know how to reverse this (remove the inner shadow) when the user unclick the search box and click elsewhere.

Thanks

I wanted to add inner shadow to a search box when the user clicks on it so I used this simple code :

function shadow()
{
document.getElementById("search2").style.boxShadow="inset 0px 0px 12px 0px rgba(0,0,0,0.75)";
}

And the markup :

<input type="search" onClick="shadow()"> 

So that when you click on the search box, the "search2" div gets an inner shadow and it works. But I want to know how to reverse this (remove the inner shadow) when the user unclick the search box and click elsewhere.

Thanks

Share Improve this question asked Apr 16, 2014 at 18:12 Marwan OssamaMarwan Ossama 3451 gold badge6 silver badges12 bronze badges 2
  • Don't do what you're doing. Your click handler should simply add/remove a class which contains the styles. Or rather, focus and blur should add/remove respectively. – Evan Davis Commented Apr 16, 2014 at 18:14
  • Unclick? Do you mean releasing the mouse button, often called mouseUp? Or do you mean clicking the mouse on anything other than the search box? – Surreal Dreams Commented Apr 16, 2014 at 18:14
Add a ment  | 

3 Answers 3

Reset to default 4

You should be using the onfocus and onblur events.

  • onfocus - fires when the user is in the textbox
  • onblur - fires when the user leaves the textbox

In the onblur event you add

document.getElementById("search2").style.boxShadow = "";

The click event only fires when the user clicks the element.

You can do this without using any JavaScript at all, using the CSS focus: pseudoselector. In your CSS styles, use this:

#search2:focus {
    box-shadow: inset 0px 0px 12px 0px rgba(0,0,0,0.75);
}

The advantage here is that it's less code and it will still work even in browsers without JavaScript enabled. Here's a jsFiddle: http://jsfiddle/5g9an/

It couldn't be simpler. Well, I can't think of a simpler method, anyhow.

Use blur event:

<input type="search" onClick="shadow()" onBlur="removeShadow()">

function removeShadow(){
  document.getElementById("search2").style.boxShadow="none";
}
发布评论

评论列表(0)

  1. 暂无评论