>  기사  >  웹 프론트엔드  >  HTML5 가이드(2) - 문서 메타데이터 운영에 대한 자세한 소개

HTML5 가이드(2) - 문서 메타데이터 운영에 대한 자세한 소개

黄舟
黄舟원래의
2017-03-22 16:01:401525검색

오늘의 내용은 문서오브젝트를 조작하는 방법에 대한 내용입니다.

 1. 문서 메타데이터 조작

먼저 관련 속성을 살펴보겠습니다.

characterSet: 현재 문서의 인코딩 방법을 가져옵니다. . 이 속성은 읽기 전용입니다.

charset: 현재 문서의 인코딩 방법을 가져오거나 설정합니다.

compatMode: 현재 문서의 호환성 모드를 가져옵니다. 쿠키: 현재 문서의 쿠키를 가져오거나 설정합니다.

defaultCharset: 브라우저의 기본 인코딩 방법을 가져옵니다.

defaultView: 현재 문서의 창 개체를 가져옵니다. >dir: 현재 문서의 텍스트 정렬을 가져오거나 설정합니다.

domain: 현재 문서의 도메인 값을 가져오거나 설정합니다.

구현: 지원되는 DOM 기능에 대한 정보를 제공합니다. 🎜>

lastModified: 문서의 마지막 수정 시간을 가져옵니다. (마지막 수정 시간이 없으면 현재 시간이 반환됩니다.)

location: 현재 문서의 URL 정보를 제공합니다. >

readyState: 현재 문서의 상태를 반환합니다. 이 속성은 읽기 전용 속성입니다.

referrer: 현재 문서에 연결된 문서 URL 정보를 반환합니다. 현재 문서의 제목을 가져오거나 설정합니다.

다음 예를 살펴보세요.

<!DOCTYPE html>
<html>
<head>
    <title>example</title>
</head>
<body>
    <script type="text/javascript">
        document.writeln(&#39;<pre class="brush:php;toolbar:false">&#39;);

        document.writeln(&#39;characterSet:&#39; + document.characterSet);
        document.writeln(&#39;charset:&#39; + document.charset);
        document.writeln(&#39;compatMode:&#39; + document.compatMode);
        document.writeln(&#39;defaultCharset:&#39; + document.defaultCharset);
        document.writeln(&#39;dir:&#39; + document.dir);
        document.writeln(&#39;domain:&#39; + document.domain);
        document.writeln(&#39;lastModified:&#39; + document.lastModified);
        document.writeln(&#39;referrer:&#39; + document.referrer);
        document.writeln(&#39;title:&#39; + document.title);

        document.write(&#39;
');

결과(브라우저마다 표시되는 결과가 다를 수 있음):

 

2. 호환성 모드를 이해하는 방법

compatMode 속성은 브라우저가 현재 문서를 처리하는 방법을 알려줍니다. 비표준 HTML이 너무 많아서 브라우저는 HTML 사양을 따르지 않더라도 이러한 페이지를 표시하려고 시도합니다. 일부 콘텐츠는 브라우저 전쟁 초기에 존재했던 고유한 기능에 의존하며 이러한 속성은 사양을 준수하지 않습니다. compatMode는 다음과 같이 하나 또는 두 개의 값을 반환합니다.

CSS1Compat: 문서는 유효한 html 사양을 준수합니다(반드시

html5

일 필요는 없으며 확인된 html4 페이지도 이 값을 반환함). 🎜>BackCompat: 문서에 사양을 준수하지 않는 기능이 포함되어 있어 호환성 모드가 실행됩니다.  

3. 위치 개체 사용

Document.location은 문서의 세부적인 주소 정보를 제공하고 다른 문서로 이동할 수 있도록 하는 위치 개체를 반환합니다. 서류. protocol: 문서 URL의 프로토콜을 가져오거나 설정합니다.

host: 문서 URL의 호스트 정보를 가져오거나 설정합니다.

href: 주소를 가져오거나 설정합니다. 문서 정보 호스트 이름: 문서의 호스트 이름을 가져오거나 설정합니다.

검색: 문서 URL의 쿼리 부분에서 정보를 가져오거나 설정합니다. >hash: 문서 URL의 해시 부분에 있는 정보를 가져오거나 설정합니다.

할당(9bb6a7d109b3f2bf35f7e2e9bd87f98a): 지정된 URL로 이동합니다.

replace(9bb6a7d109b3f2bf35f7e2e9bd87f98a) : 현재 문서를 제거하고 지정된 URL로 이동합니다.

reload(): 현재 문서를 다시 로드합니다.

resolveURL(9bb6a7d109b3f2bf35f7e2e9bd87f98a): 상대 경로를 절대 경로로 변경합니다.

다음 예를 살펴보세요.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <script type="text/javascript">
        document.writeln(&#39;<pre class="brush:php;toolbar:false">&#39;);

        document.writeln(&#39;protocol:&#39; + document.location.protocol);
        document.writeln(&#39;host:&#39; + document.location.host);
        document.writeln(&#39;hostname:&#39; + document.location.hostname);
        document.writeln(&#39;port:&#39; + document.location.port);
        document.writeln(&#39;pathname:&#39; + document.location.pathname);
        document.writeln(&#39;search:&#39; + document.location.search);
        document.writeln(&#39;hash:&#39; + document.location.hash);

        document.writeln(&#39;
');

결과:

쿠키 읽기 및 쓰기

쿠키 ​​속성을 통해 문서의 쿠키를 추가, 수정, 읽을 수 있습니다. 예:

<!DOCTYPE HTML><html><head>
    <title>Example</title>
    <meta name="author" content="Adam Freeman" />
    <meta name="description" content="A simple example" /></head><body>
    <p id="cookiedata">
    </p>
    <button id="write">
        Add Cookie</button>
    <button id="update">
        Update Cookie</button>
    <button id="clear">
        Clear Cookie</button>
    <script type="text/javascript">
        var cookieCount = 0;
        document.getElementById(&#39;update&#39;).onclick = updateCookie;
        document.getElementById(&#39;write&#39;).onclick = createCookie;
        document.getElementById(&#39;clear&#39;).onclick = clearCookie;
        readCookies();        function readCookies() {
            document.getElementById(&#39;cookiedata&#39;).innerHTML = !document.cookie ? &#39;&#39; : document.cookie;
        }        function updateCookie() {
            document.cookie = &#39;cookie_&#39; + cookieCount + &#39;=update_&#39; + cookieCount;
            readCookies();
        }        function createCookie() {
            cookieCount++;
            document.cookie = &#39;cookie_&#39; + cookieCount + &#39;=value_&#39; + cookieCount;
            readCookies();
        }        function clearCookie() {            
        var exp = new Date();
            exp.setTime(exp.getTime() - 1);            
            var arrStr = document.cookie.split("; ");            
            for (var i = 0; i < arrStr.length; i++) {                
            var temp = arrStr[i].split("=");                if (temp[0]) {
                    document.cookie = temp[0] + "=;expires=" + exp.toGMTString();
                };
            }

            cookieCount = 0;
            readCookies();
        }    </script></body></html>

결과:

 

5. ReadyState 이해

Document.readyState는 page 로드 및 구문 분석 중 페이지의 현재 상태입니다. 한 가지 기억해야 할 점은 defer 속성을 사용하여 스크립트 실행을 지연시키지 않는 한 브라우저는 스크립트 요소를 발견하자마자 즉시 실행한다는 것입니다. ReadyState에는 서로 다른 상태를 나타내는 세 가지 값이 있습니다.

로드 중: 브라우저가 문서를 로드하고 실행 중입니다.

대화형: 문서 구문 분석이 완료되었지만 브라우저가 다른 외부 리소스(미디어, 사진 등)를 로드 중입니다. >

완료: 페이지 구문 분석이 완료되었으며, 집에서 외부 리소스가 완료되었습니다.

브라우저의 전체 로딩 및 구문 분석 프로세스 동안 ReadyState의 값은 로딩, 대화형 및 완료에서 하나씩 변경됩니다. ReadyStatechange 이벤트(readyState 상태가 변경될 때 트리거됨)와 함께 사용되면 ReadyState가 매우 유용해집니다. 바인드 클릭 이벤트. 이 작업을 통해 필수

html 요소가 존재하는지 확인하고 오류 발생을 방지할 수 있습니다.

6. DOM 속성 구현에 대한 정보 얻기

  document.implementation属性帮助你了解浏览器对dom属性的实现情况。该属性返回DOMImplementation对象,对象包含hasFeature方法,你可以通过该方法了解浏览器对某属性的实现情况。


<!DOCTYPE HTML><html><head>
    <title>Example</title>
    <meta name="author" content="Adam Freeman" />
    <meta name="description" content="A simple example" /></head><body>
    <script>
        var features = ["Core", "HTML", "CSS", "Selectors-API"];        
        var levels = ["1.0", "2.0", "3.0"];
        document.writeln("<pre class="brush:php;toolbar:false">");        
        for (var i = 0; i < features.length; i++) {
            document.writeln("Checking for feature: " + features[i]);            
            for (var j = 0; j < levels.length; j++) {
                document.write(features[i] + " Level " + levels[j] + ": ");
                document.writeln(document.implementation.hasFeature(features[i], levels[j]));
            }
        }
        document.write("
")

效果:

위 내용은 HTML5 가이드(2) - 문서 메타데이터 운영에 대한 자세한 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.