我应该将作用域 CSS 放在我的主文件中,还是应该更改打印函数以适应组件的作用域 CSS?第二种情况,JS函数应该怎么改?
我将 Laravel 5 与许多 Vue 组件一起使用。在其中一个中,我有以下作用域 CSS
<style scoped>
td.not-purchased{
background-color: darkgrey;
}
td.not-assigned-here{
background-color: lightgreen;
}
td .checkbox{
margin-top: 0;
margin-bottom: 0;
display: inline-block;
}
table th:nth-child(n+3),
table td:nth-child(n+3){
width: 50px;
overflow-x: hidden;
text-overflow: ellipsis;
}
</style>
打印生成的内容时,该函数会在新页面中打开内容,并复制原始文档 HEAD 中的外部 CSS。
$(document).on('click', '.glyphicon[data-printselector]', function(){
if($(this).data('printselector') != ''){
// Print in new window
let printHtml = $($(this).data('printselector')).clone(),
printWindow = window.open(),
waitTimeout;
$(printWindow.document.body).append($('<div />', {class: 'container'}).append(printHtml));
$.each($('link'), function() {
$(printWindow.document.head).append($(this).clone());
clearTimeout(waitTimeout);
waitTimeout = setTimeout(function(){
// Here we ensure that CSS is loaded properly
printWindow.print();
printWindow.close();
}, window.changeFunctionTimeoutLong);
});
}
else
window.print();
});
我知道这可以通过将作用域 CSS 直接放入我网站的主 CSS 来实现,但我认为这违背了作用域 CSS 的全部意义。
最佳答案
默认情况下,Vue 的工作方式是,您的作用域 CSS 按以下方式转换:
- CSS 中的 CSS 选择器获得一个额外的属性选择器,CSS 本身内联在
<style>
中。标记到您的页面 - 与您的 CSS 选择器匹配的 HTML 元素被赋予相应的唯一属性
这样一来,CSS 规则的范围就限定在与唯一属性匹配的特定 HTML 元素内。
如果您希望您的作用域样式在与原始页面不同的上下文中工作,您需要做两件事来确保工作:
- HTML 元素具有必要的属性
<style>
存在具有这些属性的 CSS 标签
根据您的描述,听起来至少缺少后者。一个快速的尝试是复制所有 <style>
当您复制外部 CSS 时从您的页面添加标签,看看是否可行。
然后您可以确定这对您来说是否足够好,或者您是否真的想了解如何只抓取您需要的样式(以防您有很多样式)。
关于javascript - 我可以在打印 HTML 页面时使用 scoped CSS 吗? (使用 Laravel 和 Vue.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49028166/