<div class="wrapper"></div>
html,body {
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
@import url(//codepen.io/chrisdothtml/pen/ojLzJK.css);
// Variables
$color: #c0392b;
$color-dark: #a53125;
$speed: "0.25s";
$transition: all #{$speed} cubic-bezier(0.310, -0.105, 0.430, 1.400);
.wrapper {
display: flex;
justify-content: center;
align-items: center;
}
/* Main Styles */
.like-btn {
display: block;
background-color: $color;
width: 300px;
height: 100px;
line-height: 100px;
margin: 20px;
color: #fff;
position: relative;
top: 0;
bottom: 0;
left: 0;
right: 0;
cursor: pointer;
overflow: hidden;
border-radius: 5px;
box-shadow: 0 0 20px 0 rgba(0,0,0,.3);
transition: $transition;
span{
display: block;
height: 100%;
text-align: center;
position: absolute;
top: 0;
}
.like-text {
width: 72%;
line-height: inherit;
font-size: 22px;
text-transform: uppercase;
left: 0;
transition: $transition;
&:after {
content: '';
background-color: $color-dark;
width: 2px;
height: 70%;
position: absolute;
top: 15%;
right: -1px;
}
}
.like-icon {
line-height: inherit;
width: 28%;
right: 0;
transition: $transition;
font-size: 30px;
vertical-align: middle;
transition: $transition, height #{$speed} ease;
}
&:hover {
background-color: darken($color, 5%);
}
}
View Compiled
const createDOMFromString = (domString) => {
const div = document.createElement('div')
div.innerHTML = domString
return div
}
class LikeButton {
constructor () {
this.state = { isLiked: false }
}
setState (state) {
const oldEl = this.el
this.state = state
this.el = this.render()
if (this.onStateChange) this.onStateChange(oldEl, this.el)
}
changeLikeText () {
this.setState({
isLiked: !this.state.isLiked
})
}
render () {
this.el = createDOMFromString(`
<button class="like-btn">
<span class="like-text">${this.state.isLiked ? '取消' : '点赞'}</span>
<span class="like-icon">👍</span>
</button>
`)
this.el.addEventListener('click', this.changeLikeText.bind(this), false)
return this.el
}
}
const wrapper = document.querySelector('.wrapper')
const likeButton = new LikeButton()
wrapper.appendChild(likeButton.render()) // 第一次插入DOM元素
likeButton.onStateChange = (oldEl, newEl) => {
wrapper.insertBefore(newEl, oldEl) // 插入新的元素
wrapper.removeChild(oldEl) // 删除旧的元素
}
View Compiled
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.