如何在JavaScript中定位@media print?

时间:2014-03-19 00:17:54

标签: javascript css

我知道可以在元素上应用或删除类但是如何使用JavaScript定位CSS的@media打印?比如说一个带有两个选项的选择元素A4和Legal JavaScript将切换选择的任何选项。

示例CSS:

@media print {
    .A4 {
       ....
    }
    .Legal {
       ....
    }
}

1 个答案:

答案 0 :(得分:0)

这就是我的解决方法,我仍然更喜欢回答我的问题

<html>
<head><title></title>
<style>

</style>
<script type="text/javascript">
    function loadExternalCSS(filename) {
        var fileref = document.createElement("link");
        fileref.rel = "stylesheet";
        fileref.type = "text/css";
        fileref.href = filename;
        document.getElementsByTagName("head")[0].appendChild(fileref)
    }

    function show_applicable_print() {
        var e = document.getElementById("print-type");
        var str = e.options[e.selectedIndex].text;

        switch(str){
            case "A4":
                loadExternalCSS('print1.css')
                break;
            case "Letter":
                loadExternalCSS('print2.css')
                break;
            default:
                alert("No paper size selected.");
        }
    };
</script>
</head>
<body>
    <div id="form-main-container">
         <div class="type-of-paper">
            <table>                
            <tr><td><font>SELECT TYPE OF PAPER:</font></td></tr>
            <tr><td><select id="print-type" onchange="show_applicable_print()">
                <option value="default">--SELECT TYPE OF PAPER--</option>
                <option value="report_1">A4</option>
                <option value="report_2">Letter</option>
            </select></td></tr>
            </table> 
        </div>
    </div>
</body>
</html>

print1.css code:
@media print {#form-main-container {width: 100%; margin:0;}}

print2.css code:
@media print {#form-main-container {width: 50%; margin:0;}}