简体   繁体   English

CSS - 使 div“可点击”

[英]CSS - Make a div “clickable”

I'd like to know how i can render a div clickable (like a link, with the small hand when i go over with the mouse).我想知道如何呈现可点击的 div(就像一个链接,当我用鼠标过去时用小手)。

I have some elements like this:我有一些这样的元素:

<div class="teamSelector">Some</div>

With this jQuery:使用这个 jQuery:

$('.teamSelector').click(function() { 
    // some functions
});

Cheers干杯

You've already made it clickable in your example.你已经在你的例子中使它可点击。 If you would like it to "look" clickable, you can add some CSS:如果您希望它“看起来”可点击,您可以添加一些 CSS:

.teamSelector { cursor: pointer; }

Or continuing with jQuery:或者继续使用 jQuery:

.click(function() { do something }).css("cursor", "pointer");

Here is the W3 schools reference for the cursor property.这是光标属性的 W3 学校参考。

The css for it is:它的 css 是:

.teamSelector
{
  cursor: pointer
}

You can also add hover effects, but I'm not sure if :active will work cross-browser.您还可以添加悬停效果,但我不确定 :active 是否可以跨浏览器工作。

If you need something to be clickable, you're better off using a button or a element and styling that.如果你需要的东西,可以点击,你最好使用一个button或者a元素和造型这一点。 You can always prevent the default action with javascript.您始终可以使用 javascript 阻止默认操作。 The reason it's better is for accessibility so that users with screen readers know that there's something to interact with.它更好的原因是可访问性,以便使用屏幕阅读器的用户知道有一些东西可以与之交互。

Edit to add: When you tab through a page, you can hit the space bar to click an element.编辑添加:当您通过 Tab 键浏览页面时,您可以按空格键click一个元素。 This will not work the same on non-interactive elements, so anyone using that functionality will not be able to use whatever it is you're making.这对非交互式元素的工作方式不同,因此使用该功能的任何人都将无法使用您正在制作的任何内容。

this question is pretty old but needs some additions:这个问题很老了,但需要补充一些:

if you want to wrap component with pointer-based user interaction, you should prefer button element instead of a div (you can still display it block ).如果你想用基于指针的用户交互来包装组件,你应该更喜欢按钮元素而不是div (你仍然可以显示它block )。

<button class="teamSelector" tabindex="1">Some</button>

styles:款式:

.teamSelector{
    user-select: none; // this sets the element unselectable, unlike texts
    cursor: pointer; // changes the client's cursor
    touch-action: manipulation; // disables tap zoom delaying for acting like real button
    display: block; // if you want to display as block element
    background: transparent; //remove button style
    border: 0; //remove button style
}

Can't you just, y'know, make it a link and style it?你不能只是,你知道,把它变成一个链接并设置它的样式吗? It would be easier and accessible.它会更容易和访问。

We can show div element clickable simply by adding style=cursor:'pointer'.我们可以通过添加 style=cursor:'pointer' 来显示 div 元素可点击。 for example:例如:

  <div style="cursor: pointer;">edit</div>

It will bring small hand when we go over div element with the mouse.当我们用鼠标浏览 div 元素时,它会带来小手。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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