阅读纯JavaScript的更多链接 [英] Read more link with pure JavaScript

查看:86
本文介绍了阅读纯JavaScript的更多链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个简单的Read More示例。它由一个段落和一个按钮组成,段落的一半用span标记括起来,最初设置为隐藏。当用户单击阅读更多按钮时,将显示隐藏的跨度。我有工作代码,但只是希望像JQuery一样淡化效果,但使用纯Javascript。任何人请帮忙。

I am trying to create a simple Read More example. It consists of a paragraph and a button with half of the paragraph enclosed in a span tag which is initially set to hidden. When user clicks on Read More button the hidden span shows up. I have got the working code but just want to do a fade in effect like JQuery but with pure Javascript. Anyone please help.

var span = document.getElementsByTagName('span')[0];
var hideshow = document.getElementById('hideshow');

span.style.display = 'none';

hideshow.onclick = function() {
  span.style.display = 'block';
};

<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa maiores dolore earum ducimus molestiae, aut. <span>Quisquam consequuntur, maiores et, doloremque atque provident similique consequatur totam voluptas vitae veniam, molestiae laborum.</span></p>

<button id="hideshow">Read More</button>

推荐答案

从这里开始

span.style.opacity = 0;

您需要逐步将不透明度转换为此处。

You'll need to gradually transition the opacity to here.

span.style.opacity = 1;

您需要使用异步构造( setTimeout / setInterval / requestAnimationFrame )用于迭代,因为是同步的( / / 换中 / 的forEach )将阻止主线程,阻止浏览器实际呈现具有更新的不透明度的元素。

You'll need to use an asynchronous construct (setTimeout/setInterval/requestAnimationFrame) for iterating, because a synchronous one (while/for/for-in/forEach) will block the main thread, preventing the browser from actually rendering the element with the updated opacity.

function fadeIn(element) {

  function transition() {
    if(element.style.opacity < 1) {
      requestAnimationFrame(transition);
      element.style.opacity = Number(element.style.opacity) + 0.05;
    }
  }

  transition();
}

或者,如果您乐意使用CSS(而不是纯JS)你可以用类和过渡来做到这一点。

Alternatively, if you're happy to use CSS (rather than pure JS) you can do this with classes and transitions.

.out {
  opacity: 0;
  transition-duration: 0.5s;
}

.in {
  opacity: 1;
  transition-duration: 0.5s;
}

确保元素具有 out 类到达DOM时的类,然后当你准备淡入它时,将它交换为类中的,浏览器将处理动画对你而言。

Make sure that the element has the out class when it arrives in the DOM, then when you're ready to fade it in, swap it for the in class and the browser will handle the animation for you.

这篇关于阅读纯JavaScript的更多链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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