需求描述
HTML 结构
CSS 实现
.box { width: 150px; height: 50px; position: relative; background: pink; } .box::after { position: absolute; right: 0; bottom: 0; width: 50px; border-left: 50px solid transparent; border-bottom: 50px solid deepskyblue; content: ""; }
|
效果预览:

Javascript 封装实现
封装
let Segment = function(opt){ this.el = document.querySelector(opt.el); this.init(opt); }
Segment.prototype = { init (opt) { this.el.style.position = "relative"; this.el.style.width = `${opt.width}px`; this.el.style.height = `${opt.height}px`; this.el.style.background = opt.leftColor; this.drawRight(opt); }, drawRight (opt) { document.styleSheets[0].removeRule(`${opt.el}::after`); let deg = opt.deg > 90 ? 180 - opt.deg : opt.deg; let k = Math.tan(deg * Math.PI/180); let minK = opt.height / opt.width; k = k < minK ? minK : k; opt.rightTopWidth = deg != 90 ? opt.width / 2 - opt.height / ( 2 * k) : opt.width / 2; let cssRule = [ `position: absolute`, `right: 0`, `bottom: 0`, `width: ${opt.rightTopWidth}px`, `border-left: ${opt.width - 2 * opt.rightTopWidth}px solid transparent`, `border-bottom: ${opt.height}px solid ${opt.rightColor}`, `content: ""`, ]; opt.deg > 90 ? cssRule.push(`transform: rotateX(180deg);`) : true; document.styleSheets[0].insertRule(`${opt.el}::after{${cssRule.join(';')}}`, 0); } }
|
使用
new Segment({ el: '.box', width: 200, height: 50, leftColor: 'pink', rightColor: 'deepskyblue', deg: 135 });
|
效果预览:

Github
预览
本博客遵循署名 4.0 协议国际版 (CC BY 4.0)协议
本文链接:https://xuefeng.is-a.dev/archives/Oblique-color-block
(●'◡'●)
如果你觉得不错或者对你有帮助,
你可以替我买一杯咖啡 ☕
If you think it's good or helpful,
you can buy me a cup of coffee ☕
Ailpay
Wechat