search
HomeWeb Front-endH5 TutorialSample code sharing for practicing HTML5 CSS3Media Queries

Let’s introduce media first. To be precise, it should be CSS media queries (CSS Mediaquery), a media query contains a media type and at least one # that limits the scope of the style sheet using media attributes such as width, height, and color. ##Expression. The media query added by CSS3 allows the style to be applied to certain device ranges without modifying the content. How to define media, look at the code below, you can definitely guess it.

<!-- link元素中的CSS媒体查询 -->
<link rel="stylesheet" media="(max-width: 800px)" href="example.css" />

<!-- 样式表中的CSS媒体查询 -->
<style>@media (max-width: 600px) {
  .facet_sidebar {
    display: none;
  }
}</style>
Regarding the explanation, the document says that when the media query is true, it is relevant. Style sheets or style rules will be applied according to the normal cascading rules. Even if the media query returns false, the style sheet with the media query on the tag will still be downloaded (just not applied).

#So, this is also a drawback. If multiple style standards are defined for a certain page to respond to different media attributes, the loading time of the page will be affected. , but having said that, in the current era of rapid network development, network speed is also constantly improving and improving, so the impact is not big and can almost be ignored.

media You can use logical operators(and, not, only, etc.) to form media expressions and write more complex filtering conditions. I will not explain these expressions one by one here,

Next we will use several demos to demonstrate the usage and performance of media

##Since our purpose today is to explore how to monitor changes in the devicePixelRatio attribute. , then we can change the background style of a certain p under different devicePixelRatio values. The specific code is as follows:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <style media="screen">
            @media screen and (min-resolution: 2dppx) {
                #image {
                    background : red;
                }
            }
            @media screen and (min-resolution: 1dppx) {
                #image {
                background: #000;
            }
            }        </style>
    </head>
    <body>
        <p id="image" style="width:100px; height:100px"></p>
    </body>
</html>

The code is there, So how to test? Under normal circumstances, the devicePixelRatio attribute will not change, but there will definitely be special circumstances. For example, your computer is connected to two monitors, and the devicePixelRatio attributes of the two browsers are different. Same, then congratulations, you already have the testing conditions, just drag the page from one screen to another, so that you can see the effect and test it. Students will find that the background color of p is not as set in the code. It shows different colors under different devicePixelRatio attribute values. Why is this?

This code is the first one I wrote. After running it, I found that it had no effect. I didn’t know the reason at first. When dragging the page across the screen, in the browser console, I Found the reason. So what is the reason why the settings are invalid? Let's take a look at the screenshots of the Style content under the two screens. The left side is min-resolution equal to 1, and the right side is equal to 2

##      

Comparing the two pictures, we can find that when min-resolution is equal to 2, the properties defined in it are overwritten and do not take effect. Why is this?

To explain, I am afraid I need to add some knowledge here, that is, the specific effects of the prefixes of min- and max- in the code are described in the document. : Most media properties are prefixed with "min-" and "max-", which are used to express "greater than or equal to" and "less than or equal to". This avoids the use of "" characters that conflict with HTML and XML. If you do not specify a value for the media property, and the actual value of the property is non-zero, the expression resolves to true. Expressions containing this attribute value generally return false if the browser is running on a device that does not have this attribute value.

其实上面的说明已经帮我解释清楚了,我再通俗地和大家解释一下:当 devicePixelRatio 为 1 时,只有 min-resolution: 1dppx 这个条件满足,因此 p 的颜色是黑色没错;当 devicePixelRatio 为 2 时,两个 media 都满足条件,同时 CSS 的规则是后加载的样式将会覆盖先加载的样式,由于我么将 min-resolution: 1dppx 的 media 写在后面,因此如果两个 media 都满足条件的话, min-resolution: 1dppx 的 media 将会覆盖 min-resolution: 2dppx 的 media,因此不管你把页面拖到那个屏幕,那个 p 的背景色都是黑色。

那么我们将两个 media 调换一下位置,问题就顺利地解决了。

<style media="screen">
    @media screen and (min-resolution: 1dppx) {
        #image {
            background: #000;
        }
    }
    @media screen and (min-resolution: 2dppx) {
        #image {
            background : red;
        }
    }</style>

以上是根据不同的 media 条件设置不同的样式,这是 CSS 的做法,在 JavaScript 中,没有专门的方法来监听 window.devicePixelRatio 属性变化,那么该怎么监听 devicePixelRatio 属性的变化呢?方法也很简单,看看下面的代码,你一定就明白了:

window.matchMedia(&#39;screen and (min-resolution: 2dppx)&#39;).addListener(function(e) {
    console.info(e, window.devicePixelRatio);
});

稍微解释下,通过 window.matchMedia(‘media expression’) 方法获取到对应的 media,然后通过 addListener(function(e) {}) 来监听 media 的变化。

有玩过 Canvas 的朋友一定知道,要想绘制出来的内容效果最佳的话,Canvas 自身的 width 和 height 属性值与 style 中的 width 和 height 的比例应该恰好等于 devicePixelRatio 的值,所有如果你在切换不同 devicePixelRatio 属性值的屏幕时,没有重新设置 Canvas 的宽高的话,绘制出来的画面将不是最佳的效果。

接下来我们基于 HT for Web 的 3D 模型来做一个小实验。实验的内容是这样的,在 GraphView 中有一辆车根据某条路线前行,当拖到另外一个屏幕的时候,换辆车子。先来看看效果图:

上面两张图分别是在不同的屏幕中的截图,车子动起来的效果可以访问以下链接:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>HT for Web</title>
        <style media="screen">
            @media screen and (min-resolution: 2dppx) {}
            html, body {
                padding: 0px;
                margin: 0px;
            }        </style>
        <script src="../../oldhtforweb/lib/core/ht.js"></script>
        <script src="../../oldhtforweb/lib/plugin/ht-modeling.js"></script>
        <script src="../../oldhtforweb/lib/plugin/ht-obj.js"></script>
        <script>
            ht.Default.setImage(&#39;road&#39;, &#39;./images/road.jpg&#39;);            
            var init = function() {
                g3d = new ht.graph3d.Graph3dView();                
                var dm = g3d.dm();
                g3d.addToDOM();
                g3d.setEye(1200, 300, 0);
                g3d.getNote = function(data) {                    
                if (data.getTag() !== &#39;carNode&#39;) return null;                    
                return &#39;DevicePixelRatio : &#39; + window.devicePixelRatio;
                };                
                var carIndex = 0;
                window.matchMedia(&#39;screen and (min-resolution: 2dppx)&#39;).addListener(function() {
                    carIndex = (carIndex + 1) % 2;                    
                    var obj = result[carIndex];
                    carNode.s(&#39;shape3d&#39;, obj.name);
                    ht.Default.setDevicePixelRatio();
                });                
                var polyline = createPath(dm, 300),
                    params = {
                        delay: 0,
                        duration: 10000,
                        easing: function(t){                            
                        return (t *= 2) < 1 ? 0.5 * t * t : 0.5 * (1 - (--t) * (t - 2));
                        },
                        action: function(v, t){                            
                        var length = g3d.getLineLength(polyline);                            
                        var offset = g3d.getLineOffset(polyline, length * v),
                                point = offset.point,
                                px = point.x,
                                py = point.y,
                                pz = point.z,
                                tangent = offset.tangent,
                                tx = tangent.x,
                                ty = tangent.y,
                                tz = tangent.z;
                            carNode.p3(px, py - 9, pz);
                            carNode.lookAt([px + tx, py + ty - 9, pz + tz], &#39;front&#39;);
                        },
                        finishFunc: function(){
                            ht.Default.startAnim(params);
                        }
                    },
                    carList = [ &#39;fordFocus&#39;, &#39;concept-sedan-01v2&#39;],
                    result = [], carNode = new ht.Node();
                carNode.setTag(&#39;carNode&#39;);
                carList.forEach(function(name, index) {
                    ht.Default.loadObj(&#39;./objs/&#39;+name+&#39;/&#39;+name+&#39;.obj&#39;, &#39;./objs/&#39;+name+&#39;/&#39;+name+&#39;.mtl&#39;, {
                        cube: true,
                        center: true,
                        shape3d: name,
                        finishFunc: function(modelMap, array, rawS3) {                            
                        var k = 110 / rawS3[0];
                            rawS3 = rawS3.map(function(v) { return v * k; });
                            result[index] = {                                
                            &#39;name&#39; : name,                                
                            &#39;modelMap&#39; : modelMap,                                
                            &#39;array&#39; : array,                                
                            &#39;rawS3&#39; : rawS3
                            };                            
                            if (index === 0) {                                
                            var node = carNode;
                                node.s({                                    
                                &#39;wf.width&#39; : 0,                                    
                                &#39;shape3d&#39; : name,                                   
                                 &#39;note.position&#39; : 44,                                    
                                 &#39;note&#39; : &#39;DevicePixelRatio : &#39; + window.devicePixelRatio,     
                                 &#39;note.face&#39; : &#39;top&#39;,                                    
                                 &#39;note.autorotate&#39; : true,                            
                                  &#39;note.font&#39; : &#39;46px arial, sans-serif&#39;
                                });
                                node.s3(rawS3);
                                node.r3(0, Math.PI, 0);
                                dm.add(node);
                                polyline.setElevation(rawS3[1] * 0.5 + 2);
                                ht.Default.startAnim(params);
                            }
                        }
                    });
                });
            };            var createPath = function(dm, radius) {                
            var polyline = new ht.Polyline();
                polyline.setThickness(2);

                polyline.s({                    
                &#39;shape.border.pattern&#39;: [16, 16],                    
                &#39;shape.border.color&#39;: &#39;rgba(0, 0, 0, 0)&#39;,                    
                &#39;shape3d.resolution&#39;: 300,                    
                &#39;3d.selectable&#39;: false
                });
                dm.add(polyline);                
                var cx = 0,
                    cy = radius * Math.PI * 0.5,
                    count = 500,
                    points = [{ x: radius, y: -cy, e: 0 }],
                    segments = [1];                
                    for (var k = 0; k < count + 1; k++) {                    
                    var angle = k * Math.PI / count;
                    points.push({
                        x: cx + radius * Math.cos(angle),
                        y: cy + radius * Math.sin(angle),
                        e: 0
                    });
                    segments.push(2);
                }

                cy *= -1;
                radius *= -1;                
                for (var k = 0; k < count + 1; k++) {                    
                var angle = k * Math.PI / count;
                    points.push({
                        x: cx + radius * Math.cos(angle),
                        y: cy + radius * Math.sin(angle),
                        e: 0
                    });
                    segments.push(2);
                }

                polyline.setPoints(points);
                polyline.setSegments(segments);                
                var shape = new ht.Shape();
                shape.setPoints(points);
                shape.setSegments(segments);
                shape.s({                    
                &#39;top.visible&#39; : false,                    
                &#39;bottom.image&#39; : &#39;road&#39;,                    
                &#39;bottom.reverse.flip&#39; : true,                    
                &#39;bottom.uv.scale&#39; : [13, 1],                    
                &#39;back.visible&#39; : false,                    
                &#39;front.reverse.flip&#39; : true,                    
                &#39;3d.selectable&#39;: false
                });
                shape.setThickness(180);
                shape.setTall(15);
                shape.setClosePath(true);
                dm.add(shape);                
                return polyline;
            };        </script>
    </head>
    <body onload="init();">
    </body>
</html>

来介绍下这次 Demo 中都用到的了 HT for Web 的那些技术。

首先是车子,车子并不是通过 HT for Web 生成的,而是通过专业的 3D 工具设计,然后导出 obj 和 mtl 文件,HT for Web 对 obj 和 mtl 文件进行解析,然后显示在 Graph3dView 中,

在 obj 文档中,你会看到一个一个飞机的例子,飞机沿着设定好的路线飞行,你应该会想,这个寻路是怎么实现的呢?其实很简单,我们将路线切割成一个个很小很小的单元,然后根据算法依次获取到小单元的坐标设置到移动的物体上,这样物体就动起来了。 

在 Demo 中,有一条很精致的马路,这条马路就是一个 Shape 节点,根据车的路径生成的马路,Shape 是一个六面体,因为首尾相连了,所以没有左右面,在这个例子中,我将马路的 back 和 top  面隐藏了,然后 bottom 面支持翻转,让 bottom 面的贴图显示在内表面上,这样马路就建成了。

The above is the detailed content of Sample code sharing for practicing HTML5 CSS3Media Queries. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
H5 vs. Older HTML Versions: A ComparisonH5 vs. Older HTML Versions: A ComparisonMay 06, 2025 am 12:09 AM

The main differences between HTML5 (H5) and older versions of HTML include: 1) H5 introduces semantic tags, 2) supports multimedia content, and 3) provides offline storage functions. H5 enhances the functionality and expressiveness of web pages through new tags and APIs, such as and tags, improving user experience and SEO effects, but need to pay attention to compatibility issues.

H5 vs. HTML5: Clarifying the Terminology and RelationshipH5 vs. HTML5: Clarifying the Terminology and RelationshipMay 05, 2025 am 12:02 AM

The difference between H5 and HTML5 is: 1) HTML5 is a web page standard that defines structure and content; 2) H5 is a mobile web application based on HTML5, suitable for rapid development and marketing.

HTML5 Features: The Core of H5HTML5 Features: The Core of H5May 04, 2025 am 12:05 AM

The core features of HTML5 include semantic tags, multimedia support, form enhancement, offline storage and local storage. 1. Semantic tags such as, improve code readability and SEO effect. 2. Multimedia support simplifies the process of embedding media content through and tags. 3. Form Enhancement introduces new input types and verification properties, simplifying form development. 4. Offline storage and local storage improve web page performance and user experience through ApplicationCache and localStorage.

H5: Exploring the Latest Version of HTMLH5: Exploring the Latest Version of HTMLMay 03, 2025 am 12:14 AM

HTML5isamajorrevisionoftheHTMLstandardthatrevolutionizeswebdevelopmentbyintroducingnewsemanticelementsandcapabilities.1)ItenhancescodereadabilityandSEOwithelementslike,,,and.2)HTML5enablesricher,interactiveexperienceswithoutplugins,allowingdirectembe

Beyond Basics: Advanced Techniques in H5 CodeBeyond Basics: Advanced Techniques in H5 CodeMay 02, 2025 am 12:03 AM

Advanced tips for H5 include: 1. Use complex graphics to draw, 2. Use WebWorkers to improve performance, 3. Enhance user experience through WebStorage, 4. Implement responsive design, 5. Use WebRTC to achieve real-time communication, 6. Perform performance optimization and best practices. These tips help developers build more dynamic, interactive and efficient web applications.

H5: The Future of Web Content and DesignH5: The Future of Web Content and DesignMay 01, 2025 am 12:12 AM

H5 (HTML5) will improve web content and design through new elements and APIs. 1) H5 enhances semantic tagging and multimedia support. 2) It introduces Canvas and SVG, enriching web design. 3) H5 works by extending HTML functionality through new tags and APIs. 4) Basic usage includes creating graphics using it, and advanced usage involves WebStorageAPI. 5) Developers need to pay attention to browser compatibility and performance optimization.

H5: New Features and Capabilities for Web DevelopmentH5: New Features and Capabilities for Web DevelopmentApr 29, 2025 am 12:07 AM

H5 brings a number of new functions and capabilities, greatly improving the interactivity and development efficiency of web pages. 1. Semantic tags such as enhance SEO. 2. Multimedia support simplifies audio and video playback through and tags. 3. Canvas drawing provides dynamic graphics drawing tools. 4. Local storage simplifies data storage through localStorage and sessionStorage. 5. The geolocation API facilitates the development of location-based services.

H5: Key Improvements in HTML5H5: Key Improvements in HTML5Apr 28, 2025 am 12:26 AM

HTML5 brings five key improvements: 1. Semantic tags improve code clarity and SEO effects; 2. Multimedia support simplifies video and audio embedding; 3. Form enhancement simplifies verification; 4. Offline and local storage improves user experience; 5. Canvas and graphics functions enhance the visualization of web pages.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use