更改 el-option的樣式大家都知道加popper-class 嵌套class樣式來更改
如果想單獨更改el-option的第一個字話用偽元素:first-letter,僅限中文字
這里主要說下,如果單獨更改el-option前兩個字或者不固定字數的樣式
image.png
- 給el-option 加一個beforecontent的class名
<el-option
class="beforecontent"
v-for="(item,index) in lessonList"
:key="index"
:label="item.lessonName"
:value="index">
</el-option>
-
循環li標簽下的span加上dom節點屬性data-content和需要添加的屬性值
image.png
// 課程姓名加樣式
createLessonName() {
// 渲染章節名稱樣式
const array = document.getElementsByClassName('beforecontent');
for (let index = 0; index < array.length; index++) {
const element = array[index];
let type = this.lessonList[index].reopenStatus;
if (type && type !== 0) {
element.childNodes[0].setAttribute(
'data-content',
type === 1 ? '重開 | ' : '被重開 | '
);
// console.log(element.childNodes)
}
}
- 然后利用span偽元素的content屬性插入內容為data-content的屬性值
attr(X):定義顯示在該選擇器之前或之后的選擇器的屬性。
<style>
.el-select-dropdown__item.beforecontent span::before{
color: orange;
content: attr(data-content);
}
</style>
- el-option已經實現插入變量了,但是el-select 被選中的option個 input里是獨立的,要單獨加
原理是一樣的,但是input是閉合元素不支持偽元素
所以抓取el-select元素 給input前面加上span標簽,然后給span標簽加偽元素
所以input根據span字體空間padding-left空出位置劉給添加的內容
image.png
// 修改選擇課程名樣式
changeLessonName() {
const reopenStatus = this.activeLesson.reopenStatus;
// el-select的class名
const parent = document.getElementsByClassName('lesson-select')[0].childNodes[1];
const isSpan = parent.childNodes[1].nodeName;
if (reopenStatus && reopenStatus !== 0) {
let dom;
// 有無span節點
if (isSpan !== 'SPAN') {
dom = document.createElement('span');
dom.className = 'addspan';
parent.insertBefore(dom, parent.childNodes[1]);
}
else {
dom = parent.childNodes[1];
}
console.log(dom);
if (reopenStatus === 1) {
dom.setAttribute('data-content', '重開 | ');
parent.childNodes[2].style['padding-left'] = '37px';
}
else {
dom.setAttribute('data-content', '被重開 | ');
parent.childNodes[2].style['padding-left'] = '50px';
}
}
else {
if (isSpan === 'SPAN') {
parent.removeChild(parent.childNodes[1]);
parent.childNodes[1].style = '';
}
}
}
最后給input加上css就OK了
.lesson-select {
width: 200px;
/deep/ .addspan {
line-height: 28px;
position: absolute;
left: 5px;
&::before {
content: attr(data-content);
color:orange;
}
}
}
以上,
歡迎各位大佬指點