昨天借用了 Wired Elements
來說明什麼是 WebComponent 跟它有什麼特點
今天我們來製作一個 MyElement 吧 !
我們利用 font-awesome 製作一個 擬物型按鈕(neuomorphic button)
吧 ( ̄︶ ̄*))
[ 圖片來源 : youtube 影片 - CSS3 Neumorphism ]
首先 , 當然是建立一個 JS 檔案 , 我們叫做 neuomorphic-button.js
吧 !
// neuomorphic-button.js
建立一下我們的 Custom Html Tag
// neuomorphic-button.js
class NeuomorphicButton extends HTMLElement {
// as Component mounted to page
constructor() {
// Always call super first in constructor
super();
// Element functionality written in here
}
}
window.customElements.define('neuomorphic-button', NeuomorphicButton);
跟昨天一樣 , 在 Html 中引用自製的 Tag
<!-- use-wc.html -->
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<script src="./neuomorphic-button.js"></script>
</head>
<body>
<neuomorphic-button></neuomorphic-button>
</body>
</html>
我們先塞一些東西到 看看吧 !
// neuomorphic-button.js
class NeuomorphicButton extends HTMLElement {
// as Component mounted to page
constructor() {
// Always call super first in constructor
super();
// Element functionality written in here
const img = document.createElement('img')
img.src = 'https://raw.githubusercontent.com/andrew781026/ithome_ironman_2021/master/day-03/cat.png'
this.append(img)
}
}
window.customElements.define('neuomorphic-button', NeuomorphicButton);
回到 use-wc.html
我們可以看到一隻可愛的小貓咪 (* ̄3 ̄)╭
之後 , 我們將 img 改成 font-awesome 的 icon
// neuomorphic-button.js
class NeuomorphicButton extends HTMLElement {
// as Component mounted to page
constructor() {
// Always call super first in constructor
super();
// Element functionality written in here
const div = document.createElement('div')
div.innerHTML = `<i class="fas fa-wifi"></i>`
this.append(div)
}
}
window.customElements.define('neuomorphic-button', NeuomorphicButton);
別忘了在 use-wc.html
中引入 font-awesome 的樣式檔
<!-- use-wc.html -->
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
<script src="./neuomorphic-button.js"></script>
</head>
<body>
<neuomorphic-button></neuomorphic-button>
</body>
</html>
之後再補上 NeuomorphicButton 的邊框樣式 . 底色...等
<!-- use-wc.html -->
<!DOCTYPE html>
<html lang="zh-TW">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
<style>
.icon-box {
width: 60px;
height: 60px;
position:relative;
background-color: #ebf5fc;
box-shadow: 8px 8px 16px #bcbcbc,
0 0 8px 20px #dfe9f3,
-8px -8px 16px #ffffff;
display: flex;
justify-content: center;
align-items: center;
border-radius: 10px;
cursor: pointer;
}
.icon-box i {
font-size: 2em;
color: #6a9bd8;
}
</style>
<script src="./neuomorphic-button.js"></script>
</head>
<body>
<neuomorphic-button></neuomorphic-button>
</body>
</html>
我們的 neuomorphic-button
就顯示出來啦
如果想查看實際頁面 , 請到 first-web-component.html 查看
如果你想替換裡面的 icon , 可用下方 JS 做置換
var myTagName = 'neuomorphic-button';
document.querySelector(`${myTagName} .icon-box i`).className = 'fas fa-lightbulb'