欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

前端学习之插入脚本(html)实例教程

程序员文章站 2022-12-25 18:50:09
实现一些交互效果,数据交互的效果 大致插入的方式有三种: 第一种:行内脚本 最常见的是方式是使用事件的方式触发, 1.事件触发,例如:

实现一些交互效果,数据交互的效果

大致插入的方式有三种:

第一种:行内脚本

最常见的是方式是使用事件的方式触发,

1.事件触发,例如:<input type="button" onclick="window.alert("hello word!")">;

2.javascript伪协议,例如:<a href="javascript:alert('hello world!');return false">hello</a>

第二种:内嵌脚本

这种主要通过script方式内嵌,例如

<script>

    var text="hello world!"

    document.write('<p>'+text+'</p>');

</script>

内嵌注意:

<script>

    var text="hello world!"

    document.write('<p>'+text+'</p>');    

    document.write('<script src='as.js'></script>');    //这种写法是错误的,因为这一行包含了一个</script>标签,会默认认为这是一个闭合标签,正确写法应该是document.write('<script src='as.js'></scr'+'ipt>');使用字符串的方式拼接,或者: document.write('<script src='as.js'>&lt;/script>');,将<号使用实体字符转义 

</script>

第三种:外联脚本   

<script>元素实现,需要将js代码放在js文件中,通过src这个属性引用进来,type的值默认text/javascript,实际应用中不建议写

在es6中加入了一个重要的特性叫做,module(模块化),载入其他模块的方式(es6为例)

<script type="module">

inport{test,greet} from "../js/as.js"

</script>

export function test(){

}

export function greet(){

}

我们把type类型为javascript的称为classic scripts,把type类型为module成为module scripts

                               脚本类型(通常不写)                              跨域文本处理                执行脚本方式

<script src="as.js"  type="text/javascript" charst="utf-8" crossorigin="anonymous" async defer></script>

          脚本引用地址                                   编码方式(可以不写)

                               脚本类型                 跨域文本处理          执行脚本方式

<script src="as.js"  type="module"   crossorigin="anonymous" async></script>

          脚本引用地址                                

async/defer执行方式

这两个属性都是布尔属性,要么true,要么false,

async:立即执行

defer:html文件解析完才可以执行

假如同时存在,优先async规则

课后练习

使用js的方式,实现响应式

提示:window.onresize,window.clientwidth,element.classname

方法一:

    <script>

        window.onresize=function () {

            //alert(width());

            if (width()>=700){

                document.getelementbyid("p1").classname="p1";

                document.getelementbyid("p2").classname="p2";

            }

            else if(width()<700){

                document.getelementbyid("p1").classname="p3";

                document.getelementbyid("p2").classname="p4";

            }

        };

        function width() {

            var widthmax=document.body.clientwidth;

            return widthmax;

        }

    </script>

解释:通过window.onresize方法实时判断窗口是否有改变,然后通过document.body.clientwidth方法获得窗口的宽度,根据不同的宽度调整样式;

但是这里遇到几个问题:(1)onresize多次触发的问题,当改变窗口大小时,onresize被触发了多次;(2)这个调整比较麻烦,假如元素过多时,调整很麻烦;

因此,修改一下要求,改成:还是响应式,但是根据窗口的大小,动态创建css文件引入,已达到响应的效果