Greasemonkey如何仅在@media print中应用CSS规则?

3

我正在使用Greasemonkey和JQuery的#css方法向页面添加CSS样式。到目前为止,脚本如下:

// ==UserScript==
// @name           www.al-anon.dk Remove inline scroll so that page content prints properly
// @namespace      http://userscripts.org/users/103819
// @description    remove scroll from al-anon pages
// @include        http://al-anon.dk/*
// @require        http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
// ==/UserScript==

$('#framen').css({'height': 'auto', width: 'auto'});
$('#menu').css({ 'display': 'none'});

现在我的问题是如何仅将最后一条规则应用于@media print?

换句话说:如果这是干净的CSS,我会使用以下语法:

@media print {
  /* style sheet for print goes here */
}

但是如何使用Greasemonkey/JQuery实现这一点?
2个回答

3
GM_addStyle('@media print { #menu { display:none; } }');

如果您希望您的脚本在其他浏览器中运行。

/**
 * Define GM_addStyle function if one doesn't exist
 */
if( typeof GM_addStyle != 'function' )
function GM_addStyle(css)
{
    var style = document.createElement('style');
    style.innerHTML = css;
    style.type='text/css';
    document.getElementsByTagName('head')[0].appendChild(style);
}

3
您可以使用附加样式元素的方法来实现:
$('<style media="print">#menu {display: none;}</style>').appendTo('head');

是的,我知道。但是有没有办法使用其他JQuery方法与#css方法一起使用? - Jesper Rønn-Jensen
在这种特定情况下(我只想添加一条简单规则),我很可能会接受您的答案。如果有更好的解决方案出现,我会把问题保持开放状态:) - Jesper Rønn-Jensen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接