单独使用CSS增加点击时的div大小 [英] Increase a div size on click with css alone

查看:330
本文介绍了单独使用CSS增加点击时的div大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在单击div时增加其宽度。我想仅通过CSS来实现。可能吗?我通过悬停使它的宽度增加了,但是当我单击div时,我需要同样的效果。

I want to increase the width of my div when I click on it. I want to achieve this with CSS alone. Is it possible? I made it increase in width via hover, but I need the same effect to happen when I click on the div. Suggestions are appreciated.

HTML

<div id="sample"></div>

CSS

#sample{
  width:100px;
  height:100px;
  background:#000000;
}

我想在单击时将宽度更改为200px。

I want to change the width to 200px on click.

推荐答案

一种可能的解决方案是在 tabindex 属性> div ,就像这样:

One potential solution would be to add a tabindex attribute to the div, like so:

<div id="sample" tabindex="0"></div>

现在,您可以在:focus 中使用您的CSS:

Now, you can use :focus in your CSS:

#sample:focus {
   width: 200px;
}

这是一个显示操作的jsFiddle

不幸的是,当 div 被模糊,宽度将返回。 更新:请查看 Shaggy's Answer ,这是一种保持聚焦效果的聪明解决方案。

Unfortunately, when the div is blurred, the width will go back. Update: check out Shaggy's Answer for a clever solution to retaining the focus effect.

如果您需要在 div 模糊之后保持宽度,您可能必须冒险使用JavaScript / jQuery,或者只需添加 onclick 属性。

If you need the width to stay after the div is blurred, you will likely have to venture into JavaScript/jQuery, or just add an onclick attribute.

<div id="sample" onclick="this.style.width = '200px';"></div>

这篇关于单独使用CSS增加点击时的div大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆