Jquery均匀地调整锚文本的大小

时间:2016-06-03 14:50:07

标签: javascript jquery

我试图均匀增加然后减少段落内锚文本的字体大小而不移动段落文本。这样,锚文本看起来好像是朝向用户,然后后退回原来的位置。字体大小也显示为从左下角开始生长,而不是我想要的,从各个方面均匀地生长。

HTML:

<p>
  <a>[D]</a>I've been workin' on the railroad,
  <a>[G]</a>all the live long <a>[D]</a>day.
  <a>[D]</a>I've been workin' on the railroad,
  just to <a>[E]</a>pass the time a<a>[A]</a>way.
</p>

CSS:

p {
  white-space: pre-wrap;
}

a {
  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
  color:red;
}
.increase-font {
  font-size: 30px;
  background:#FFF;
}

Jquery的/使用Javascript:

$('a').on('click',function(e){
  e.preventDefault();
  var el = this;
  $(el).addClass('increase-font');
  setTimeout(function(){  
   $(el).removeClass('increase-font');
  },1000);
});

这是小提琴:

https://jsfiddle.net/scooke/ro2tyf6h/

2 个答案:

答案 0 :(得分:0)

它相对简单 - 只需将锚标记包装在span标记中:

<p><a><span>[D]</span></a>I've been workin' on the railroad,</p>
<p><a><span>[G]</span></a>all the live long <a><span>[D]</span></a>day.</p>
<p><a><span>[D]</span></a>I've been workin' on the railroad, just to <a><span>[E]</span></a>pass the time a<a><span>[A]</span></a>way.</p>

将锚点的位置设置为相对(使用边距以使其子项跨越空间),同时还将span标记设置为绝对值:

a {
  position: relative;
  max-height: 0px;
  max-width: 0px; 
  margin-right: 25px;
}

span {
  position: absolute;
  top: 0;
  left: 0;
}

然后只需将jQuery事件处理程序从所有锚标记注册到所有span标记:

$('span').on('click',function(e){
  e.preventDefault();
  var el = this;
  $(el).addClass('increase-font');
  setTimeout(function(){  
   $(el).removeClass('increase-font');
  },1000);
})

从DOM流中删除绝对元素,调整跨度大小不会影响它周围的元素。完整代码:

https://jsfiddle.net/ro2tyf6h/5/

答案 1 :(得分:0)

要实现这一点,锚文本需要在某种程度上独立于父级。使用CSS :before:after选择器插入锚文本将解决问题。查看我的示例并根据需要进行调整。

$('a').on('click', function(e) {
  e.preventDefault();
  var el = this;
  $(el).addClass('increase-font');
  setTimeout(function() {
    $(el).removeClass('increase-font');
  }, 1000);
})
p {
  white-space: pre-wrap;
  padding-left: 30px;
  display: inline-block;
  width: 100%;
  position: relative;
}
a {
  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
  color: red;
  display: inline-block;
  position: relative;
  width: 30px;
  height: 10px;
}
a:before {
  content: "[D]";
  position: absolute;
  left: 0;
  text-align: center!important;
  width: 100%;
  top: -5px;
}
.increase-font {
  font-size: 30px;
  background: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <p> <a></a>I've been workin' on the railroad,</p>
  <p><a></a>all the live long <a></a>day.</p>
  <p><a></a>I've been workin' on the railroad, just to <a></a>pass the time a<a></a>way.</p>

<强>建议:

  1. 重新构建HTML将是一个良好的开端
  2. :hover状态添加背景将有助于保持其清洁 并且可以区分。