【问题标题】:Making only picture clickable css/html inside header只在标题内制作图片可点击的css/html
【发布时间】:2014-05-19 18:20:05
【问题描述】:

我正在开发一个响应式网站,但遇到了一个烦人的问题。在我的标题中有一些文字。我用 text-indent -9999px 将它设置在屏幕外。之后我加载背景图像。但我只希望背景图像是可点击的。我不知道该怎么做。我在谷歌上找到了一些例子。但他们从不“注入”带有 css 的图片。他们总是在 html 中定义图片。

所以我想要的只是在标题中水平居中的图片,只有图片是可点击的,而不是它周围的边距。

<header>
<a href="alink">
<h1>this is gonna be replaced with an image(on desktop websites). It will stay here on mobile website</h1></a>
</header>

和css:

header h1 {
margin:10px 0 30px 0;
text-indent:-9999px;
background-image: url('pika.png');
background-repeat: no-repeat;
background-size: contain;
background-position:50% 50%;
width:100%;
height:220px;
border:1px solid red;
float: left;
}

我还将代码上传到 jsfiddle: http://jsfiddle.net/Cm3yQ/

如你所见,目前整个h1都是可点击的,我只希望图片是可点击的。

【问题讨论】:

  • 我不认为有任何简单的解决方案,这里的另一个相关问题是如果你有一个龙的图像而不是那个皮卡丘怎么办? 甚至更多复杂的图像?您可能必须手动为图像中的重要点构建地图并使用ismapusemap 属性(用于锚点),这意味着如果图像发生更改,您必须重新构建地图.
  • 您已将 h1 设置为 100% 宽度乘以 220 像素高度,因此,这就是“可点击”。如果您只希望标题与背景图像一样宽/高,则相应地更改宽度和高度。
  • 但如果我将其设置为小于 100%,它就不再位于我的屏幕中心。它转到我屏幕的左侧。

标签: html css image center


【解决方案1】:

&lt;edit&gt;

只有图片可点击的可能性是:

  1. 使用img+map+area
  2. 或使用SVG。一个随机教程:http://tutorials.jenkov.com/svg/a-element.html 可以做的平均示例:DEMO

&lt;/edit&gt;


您应该将链接包装在h1 中,并给它一个display:block

header {
  background:url(http://lorempixel.com/400/150);
  /* background could either be on h1 or a */
  background-size:cover;/* optionnal */
}
header, h1 , h1 a  {/* size them all at once */
  display:block;
  height:300px;
}
a {
  text-indent:-9999px;/* hide text from screen */
  /* still not working ? set background here or give it a color 
  almost transparent so it can catch click event : 
  background:rgba(0,0,0,0.001);*/
}

和 HTML:

<header>
  <h1>
    <a href="#"> SOME text </a>
  </h1>
</header>

【讨论】:

  • 但是我想在标题的中心放一个小图片,你的例子可以吗?因为现在我又有了一个完全可点击的标题。
  • 对不起,我错过了您只希望图像可点击的部分。
  • 对于你想要的,你需要使用 SVG,无论如何,图像必须是 HTML 格式。最常用的方法是使用
  • 我有一个 psd photoshop 格式的文件。我可以将其导出为 svg,然后一切正常吗?
  • 稍微复杂一点,你需要设置可点击区域并给它一个xlink。我去找英文教程
【解决方案2】:

它可能看起来像评论,但我没有足够的声誉来发表评论,因此我把它作为答案。

为什么不在 html 中创建另一个 div 并将图像放入其中,然后相应地设置样式。

【讨论】:

  • 那么您为什么不尝试编辑 OP 发布的小提琴并将其发布在您的答案中?
【解决方案3】:

HTML

<header>
<div class="headerDiv">
    <a href="anotherfile"><h1>this is gonna be replaced with an image(on desktop website). It will stay here on mobile website</h1></a>
</div>
</header>

CSS

.headerDiv{
 border:1px solid red;
 height:220px;
 width:100%;    
}

header h1 {
 margin:10px 0 30px 0;
 text-indent:-9999px;
 background-image:      url('http://img3.wikia.nocookie.net/__cb20120630141813/sims/images/d/d7/Pichu.gif');
 background-repeat: no-repeat;
 background-size: contain;
 background-position:center; 

 height:220px;
 // float: left;    Get Rid of float: left
}

【讨论】:

  • 但是现在整个标题又可以点击了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-20
  • 2015-06-11
  • 2011-06-30
  • 2016-09-16
  • 2021-07-02
  • 2014-12-14
相关资源
最近更新 更多