前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >专栏 >Laravel5.2之Seeder填充数据小技巧

Laravel5.2之Seeder填充数据小技巧

作者头像
botkenni
发布于 2022-01-10 01:24:08
发布于 2022-01-10 01:24:08
3.6K00
代码可运行
举报
文章被收录于专栏:IT码农IT码农
运行总次数:0
代码可运行

说明:本文主要聊一聊Laravel测试数据填充器Seeder的小技巧,同时介绍下Laravel开发插件三件套,这三个插件挺好用哦。同时,会将开发过程中的一些截图和代码黏上去,提高阅读效率。

备注:在设计个人博客软件时,总会碰到有分类Category、博客Post、给博客贴的标签Tag、博客内容的评论Comment。 而且,Category与Post是一对多关系One-Many:一个分类下有很多Post,一个Post只能归属于一个Category;Post与Comment是一对多关系One-Many:一篇博客Post下有很多Comment,一条Comment只能归属于一篇Post;Post与Tag是多对多关系Many-Many:一篇Post有很多Tag,一个Tag下有很多Post。 开发环境:Laravel5.2 + MAMP + PHP7 + MySQL5.5

开发插件三件套

在先聊测试数据填充器seeder之前,先装上开发插件三件套,开发神器。先不管这能干些啥,装上再说。 1、barryvdh/laravel-debugbar

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
composer require barryvdh/laravel-debugbar --dev

2、barryvdh/laravel-ide-helper

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
composer require barryvdh/laravel-ide-helper --dev

3、mpociot/laravel-test-factory-helper

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
composer require mpociot/laravel-test-factory-helper --dev

然后在config/app.php文件中填上:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
        /**
         *Develop Plugin
        */
        Barryvdh\Debugbar\ServiceProvider::class,
        Mpociot\LaravelTestFactoryHelper\TestFactoryHelperServiceProvider::class,
        Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,

设计表的字段和关联

设计字段

按照上文提到的Category、Post、Comment和Tag之间的关系创建迁移Migration和模型Model,在项目根目录输入:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
php artisan make:model Category -m
php artisan make:model Post -m
php artisan make:model Comment -m
php artisan make:model Tag -m

在各个表的迁移migrations文件中根据表的功能设计字段:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
//Category表
class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->comment('分类名称');
            $table->integer('hot')->comment('分类热度');
            $table->string('image')->comment('分类图片');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('categories');
    }
}
    
//Post表
class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('category_id')->unsigned()->comment('外键');
            $table->string('title')->comment('标题');
            $table->string('slug')->unique()->index()->comment('锚点');
            $table->string('summary')->comment('概要');
            $table->text('content')->comment('内容');
            $table->text('origin')->comment('文章来源');
            $table->integer('comment_count')->unsigned()->comment('评论次数');
            $table->integer('view_count')->unsigned()->comment('浏览次数');
            $table->integer('favorite_count')->unsigned()->comment('点赞次数');
            $table->boolean('published')->comment('文章是否发布');
            $table->timestamps();
            //Post表中category_id字段作为外键,与Category一对多关系
            $table->foreign('category_id')
                  ->references('id')
                  ->on('categories')
                  ->onUpdate('cascade')
                  ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //删除表时要删除外键约束,参数为外键名称
        Schema::table('posts', function(Blueprint $tabel){
            $tabel->dropForeign('posts_category_id_foreign');
        });
        Schema::drop('posts');
    }
}

//Comment表
class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id')->unsigned()->comment('外键');
            $table->integer('parent_id')->comment('父评论id');
            $table->string('parent_name')->comment('父评论标题');
            $table->string('username')->comment('评论者用户名');
            $table->string('email')->comment('评论者邮箱');
            $table->string('blog')->comment('评论者博客地址');
            $table->text('content')->comment('评论内容');
            $table->timestamps();
            //Comment表中post_id字段作为外键,与Post一对多关系
            $table->foreign('post_id')
                  ->references('id')
                  ->on('posts')
                  ->onUpdate('cascade')
                  ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
    //删除表时要删除外键约束,参数为外键名称
        Schema::table('comments', function(Blueprint $tabel){
            $tabel->dropForeign('comments_post_id_foreign');
        });
        Schema::drop('comments');
    }
}

//Tag表
class CreateTagsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tags', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name')->comment('标签名称');
            $table->integer('hot')->unsigned()->comment('标签热度');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('tags');
    }
}

由于Post表与Tag表是多对多关系,还需要一张存放两者关系的表:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
//多对多关系,中间表的命名laravel默认按照两张表字母排序来的,写成tag_post会找不到中间表
php artisan make:migration create_post_tag_table --create=post_tag

然后填上中间表的字段:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class CreatePostTagTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('post_tag', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('post_id')->unsigned();
            $table->integer('tag_id')->unsigned();
            $table->timestamps();
            //post_id字段作为外键
            $table->foreign('post_id')
                  ->references('id')
                  ->on('posts')
                  ->onUpdate('cascade')
                  ->onDelete('cascade');
            //tag_id字段作为外键      
            $table->foreign('tag_id')
                  ->references('id')
                  ->on('tags')
                  ->onUpdate('cascade')
                  ->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('post_tag', function(Blueprint $tabel){
            $tabel->dropForeign('post_tag_post_id_foreign');
            $tabel->dropForeign('post_tag_tag_id_foreign');
        });
        Schema::drop('post_tag');
    }
}
设计关联

写上Migration后,还得在Model里写上关联:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class Category extends Model
{
    //Category-Post:One-Many
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model
{
    //Post-Category:Many-One
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    //Post-Comment:One-Many
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    //Post-Tag:Many-Many
    public function tags()
    {
        return $this->belongsToMany(Tag::class)->withTimestamps();
    }
}

class Comment extends Model
{
    //Comment-Post:Many-One
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

class Tag extends Model
{
    //Tag-Post:Many-Many
    public function posts()
    {
        return $this->belongsToMany(Post::class)->withTimestamps();
    }
}

然后执行迁移:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
php artisan migrate

数据库中会生成新建表,表的关系如下:

Seeder填充测试数据

好,在聊到seeder测试数据填充之前,看下开发插件三件套能干些啥,下文中命令可在项目根目录输入php artisan指令列表中查看。 1、barryvdh/laravel-ide-helper 执行php artisan ide-helper:generate指令前:

执行php artisan ide-helper:generate指令后:

不仅Facade模式的Route由之前的反白了变为可以定位到源码了,而且输入Config Facade时还方法自动补全auto complete,这个很方便啊。

输入指令php artisan ide-helper:models后,看看各个Model,如Post这个Model:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Post
 *
 * @property integer $id
 * @property integer $category_id 外键
 * @property string $title 标题
 * @property string $slug 锚点
 * @property string $summary 概要
 * @property string $content 内容
 * @property string $origin 文章来源
 * @property integer $comment_count 评论次数
 * @property integer $view_count 浏览次数
 * @property integer $favorite_count 点赞次数
 * @property boolean $published 文章是否发布
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 * @property-read \App\Category $category
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Comment[] $comments
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Tag[] $tags
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereCategoryId($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereTitle($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereSlug($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereSummary($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereContent($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereOrigin($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereCommentCount($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereViewCount($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereFavoriteCount($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post wherePublished($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereCreatedAt($value)
 * @method static \Illuminate\Database\Query\Builder|\App\Post whereUpdatedAt($value)
 * @mixin \Eloquent
 */
class Post extends Model
{
    //Post-Category:Many-One
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    //Post-Comment:One-Many
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }

    //Post-Tag:Many-Many
    public function tags()
    {
        return $this->belongsToMany(Tag::class)->withTimestamps();
    }
}

根据迁移到库里的表生成字段属性和对应的方法提示,在控制器里输入方法时会自动补全auto complete字段属性的方法:

2、mpociot/laravel-test-factory-helper 输入指令php artisan test-factory-helper:generate后,database/factory/ModelFactory.php模型工厂文件会自动生成各个模型对应字段数据。Faker是一个好用的生成假数据的第三方库,而这个开发插件会自动帮你生成这些属性,不用自己写了。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
<?php

/*
|--------------------------------------------------------------------------
| Model Factories
|--------------------------------------------------------------------------
|
| Here you may define all of your model factories. Model factories give
| you a convenient way to create models for testing and seeding your
| database. Just tell the factory how a default model should look.
|
*/

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'email' => $faker->safeEmail,
        'password' => bcrypt(str_random(10)),
        'remember_token' => str_random(10),
    ];
});
$factory->define(App\Category::class, function (Faker\Generator $faker) {
    return [
        'name' =>  $faker->name ,
        'hot' =>  $faker->randomNumber() ,
        'image' =>  $faker->word ,
    ];
});

$factory->define(App\Comment::class, function (Faker\Generator $faker) {
    return [
        'post_id' =>  function () {
             return factory(App\Post::class)->create()->id;
        } ,
        'parent_id' =>  $faker->randomNumber() ,
        'parent_name' =>  $faker->word ,
        'username' =>  $faker->userName ,
        'email' =>  $faker->safeEmail ,
        'blog' =>  $faker->word ,
        'content' =>  $faker->text ,
    ];
});

$factory->define(App\Post::class, function (Faker\Generator $faker) {
    return [
        'category_id' =>  function () {
             return factory(App\Category::class)->create()->id;
        } ,
        'title' =>  $faker->word ,
        'slug' =>  $faker->slug ,//修改为slug
        'summary' =>  $faker->word ,
        'content' =>  $faker->text ,
        'origin' =>  $faker->text ,
        'comment_count' =>  $faker->randomNumber() ,
        'view_count' =>  $faker->randomNumber() ,
        'favorite_count' =>  $faker->randomNumber() ,
        'published' =>  $faker->boolean ,
    ];
});

$factory->define(App\Tag::class, function (Faker\Generator $faker) {
    return [
        'name' =>  $faker->name ,
        'hot' =>  $faker->randomNumber() ,
    ];
});

在聊第三个debugbar插件前先聊下seeder小技巧,用debugbar来帮助查看。Laravel官方推荐使用模型工厂自动生成测试数据,推荐这么写的:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
//先输入指令生成database/seeds/CategoryTableSeeder.php文件: php artisan make:seeder CategoryTableSeeder
<?php

use Illuminate\Database\Seeder;

class CategoryTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        factory(\App\Category::class, 5)->create()->each(function($category){
            $category->posts()->save(factory(\App\Post::class)->make());
        });
    }
}
//然后php artisan db:seed执行数据填充

但是这种方式效率并不高,因为每一次create()都是一次query,而且每生成一个Category也就对应生成一个Post,当然可以在each()里每一次Category继续foreach()生成几个Post,但每一次foreach也是一次query,效率更差。可以用debugbar小能手看看。先在DatabaseSeeder.php文件中填上这次要填充的Seeder:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
        $this->call(CategoryTableSeeder::class);
    }

路由文件中写上:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
Route::get('/artisan', function () {
    $exitCode = Artisan::call('db:seed');
    return $exitCode;
});

输入路由/artisan后用debugbar查看执行了15次query,耗时7.11ms:

实际上才刚刚输入几个数据呢,Category插入了10个,Post插入了5个。 可以用DB::table()->insert()批量插入,拷贝ModelFactory.php中表的字段定义放入每一个表对应Seeder,当然可以有些字段为便利也适当修改对应假数据。

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class CategoryTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
//        factory(\App\Category::class, 20)->create()->each(function($category){
//            $category->posts()->save(factory(\App\Post::class)->make());
//        });

        $faker = Faker\Factory::create();
        $datas = [];
        foreach (range(1, 10) as $key => $value) {
            $datas[] = [
                'name' =>  'category'.$faker->randomNumber() ,
                'hot' =>  $faker->randomNumber() ,
                'image' =>  $faker->url ,
                'created_at' => \Carbon\Carbon::now()->toDateTimeString(),
                'updated_at' => \Carbon\Carbon::now()->toDateTimeString()
            ];
        }
        DB::table('categories')->insert($datas);
    }
}

class PostTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();
        $category_ids = \App\Category::lists('id')->toArray();
        $datas = [];
        foreach (range(1, 10) as $key => $value) {
            $datas[] = [
                'category_id' => $faker->randomElement($category_ids),
                'title' =>  $faker->word ,
                'slug' =>  $faker->slug ,
                'summary' =>  $faker->word ,
                'content' =>  $faker->text ,
                'origin' =>  $faker->text ,
                'comment_count' =>  $faker->randomNumber() ,
                'view_count' =>  $faker->randomNumber() ,
                'favorite_count' =>  $faker->randomNumber() ,
                'published' =>  $faker->boolean ,
                'created_at' => \Carbon\Carbon::now()->toDateTimeString(),
                'updated_at' => \Carbon\Carbon::now()->toDateTimeString()
            ];
        }
        DB::table('posts')->insert($datas);
    }
}

class CommentTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();
        $post_ids = \App\Post::lists('id')->toArray();
        $datas = [];
        foreach (range(1, 50) as $key => $value) {
            $datas[] = [
                'post_id' => $faker->randomElement($post_ids),
                'parent_id' =>  $faker->randomNumber() ,
                'parent_name' =>  $faker->word ,
                'username' =>  $faker->userName ,
                'email' =>  $faker->safeEmail ,
                'blog' =>  $faker->word ,
                'content' =>  $faker->text ,
                'created_at' => \Carbon\Carbon::now()->toDateTimeString(),
                'updated_at' => \Carbon\Carbon::now()->toDateTimeString()
            ];
        }
        DB::table('comments')->insert($datas);
    }
}

class TagTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();
        $datas = [];
        foreach (range(1, 10) as $key => $value) {
            $datas[] = [
                'name' =>  'tag'.$faker->randomNumber() ,
                'hot' =>  $faker->randomNumber() ,
                'created_at' => \Carbon\Carbon::now()->toDateTimeString(),
                'updated_at' => \Carbon\Carbon::now()->toDateTimeString()
            ];
        }
        DB::table('tags')->insert($datas);
    }
}

class PostTagTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker\Factory::create();
        $post_ids = \App\Post::lists('id')->toArray();
        $tag_ids = \App\Tag::lists('id')->toArray();
        $datas = [];
        foreach (range(1, 20) as $key => $value) {
            $datas[] = [
                'post_id' =>  $faker->randomElement($post_ids) ,
                'tag_id' =>  $faker->randomElement($tag_ids) ,
                'created_at' => \Carbon\Carbon::now()->toDateTimeString(),
                'updated_at' => \Carbon\Carbon::now()->toDateTimeString()
            ];
        }
        DB::table('post_tag')->insert($datas);
    }
}

在DatabaseSeeder.php中按照顺序依次填上Seeder,顺序不能颠倒,尤其有关联关系的表:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
class DatabaseSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UsersTableSeeder::class);
        $this->call(CategoryTableSeeder::class);
        $this->call(PostTableSeeder::class);
        $this->call(CommentTableSeeder::class);
        $this->call(TagTableSeeder::class);
        $this->call(PostTagTableSeeder::class);
    }
}

输入路由/artisan后,生成了10个Category、10个Post、50个Comments、10个Tag和PostTag表中多对多关系,共有9个Query耗时13.52ms:

It is working!!!

表的迁移Migration和关联Relationship都已设计好,测试数据也已经Seeder好了,就可以根据Repository模式来设计一些数据库逻辑了。准备趁着端午节研究下Repository模式的测试,PHPUnit结合Mockery包来TDD测试也是一种不错的玩法。M(Model)-V(View)-C(Controller)模式去组织代码,很多时候也未必指导性很强,给Model加一个Repository,给Controller加一个Service,给View加一个Presenter,或许代码结构更清晰。具体可看下面分享的一篇文章。

最近一直在给自己充电,研究MySQL,PHPUnit,Laravel,上班并按时打卡,看博客文章,每天喝红牛。很多不会,有些之前没咋学过,哎,头疼。后悔以前读书太少,书到用时方恨少,人丑还需多读书。

分享下最近发现的一张好图和一篇极赞的文章:

文章链接:Laravel的中大型專案架構

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016/10/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
iframe自适应高度_iframe根据内容自适应高度
首先需要给iframe设置一个id,不需要滚动条则加上scrolling=”no”
全栈程序员站长
2022/11/08
5.1K0
iframe 自适应高度的多种实现方式
需求:实现 iframe 的自适应高度,能够随着页面的长度自动的适应以免除页面和 iframe 同时出现滚动条的现象。
全栈程序员站长
2022/09/06
7.7K0
iframe的高度自适应_div自适应高度
大家好,又见面了,我是你们的朋友全栈君。 Demo页面:主页面 iframe_a.html ,被包含页面 iframe_b.htm 和 iframe_c.html
全栈程序员站长
2022/11/04
7.2K0
iframe自适应高度和宽度_自适应框架
var ifm_content = document.getElementById(“conFrame”);
全栈程序员站长
2022/11/19
2.9K0
iframe自适应高度 原
同时总结下经常用的高度           contentWindow   兼容各个浏览器,可取得子窗口的 window 对象。             contentDocument Firefox 支持,> ie8 的ie支持。可取得子窗口的 document 对象。             document.body.clientWidth  可见区域内容的宽度(不包含边框,如果水平有滚动条,不显示全部内容的宽度)           document.body.clientHeight 全部内容的高度(如果垂直有滚动条,也显示全部内容的高度)           document.body.offsetWidth  可见区域内容的宽度(含边框,如果水平有滚动条,不显示全部内容的宽度)           document.body.offsetHeight 全部内容的高度(如果垂直有滚动条,也显示全部内容的高度)           document.body.scrollWidth  内容的宽度(含边框,如果有滚动则是包含整个页面的内容的宽度,即拖动滚动条后看到的所有内容)           document.body.scrollHeight 全部内容的高度
tianyawhl
2019/04/04
2.3K0
iframe标签属性说明 详解[通俗易懂]
Iframe 标签详解<Iframe src=”example.htm” width=”300″ heitht=”100″></IFRAME> example.htm 是被嵌入的页面,标签 <IFRAME> 还有一些可用的参数设置如下: marginwidth:网页中内容在表格右侧的预留宽度;例如:marginwidth=”20″,单位是 pix,下同。 marginheight:网页中内容在表格顶部预留的高度; hspace:网页右上角的的横坐标; vspace:网页右上角的纵坐标; frameborder:是否显示边缘;填”1″表示”是”,填”0″表示”否” scrolling:是否出现滚动条;填”1″表示”是”,填”0″表示”否” 在HTM(HTML)文件中是否可以像PHP、ASP文件一样嵌入其他文件呢?下面笔者介绍用iframe来实现的方法。 iframe元素的功能是在一个文档里内嵌一个文档,创建一个浮动的帧。其部分属性简介如下: name:内嵌帧名称 width:内嵌帧宽度(可用像素值或百分比) height:内嵌帧高度(可用像素值或百分比) frameborder:内嵌帧边框 marginwidth:帧内文本的左右页边距 marginheight:帧内文本的上下页边距 scrolling:是否出现滚动条(“auto”为自动,“yes”为显示,“no”为不显示) src:内嵌入文件的地址 style:内嵌文档的样式(如设置文档背景等) allowtransparency:是否允许透明 明白了以上属性后,我们可用以下代码实现,在main.htm中把samper.htm文件的内容显示在一个高度为80、宽度为100%、自动显示边框的内嵌帧中 让iframe自动适应内容的高度
全栈程序员站长
2022/08/01
3.5K0
JavaScript 处理Iframe自适应高度的问题
 用到的就是iframe嵌套的页面加载完毕的时候,运用onload事件来获取嵌套在iframe中网页的高度,然后赋值给Iframe的高度即可。
aehyok
2018/09/11
1.6K0
不使用定时器实现iframe的自适应高度
在微博上看到有人提及不使用定时器实现iframe自适应(onReadyStateChange + onLoad + onResize + onDOMSubtreeModified),然后就去折腾了,这篇与之前的文章:《不使用定时器实现onhashchange》有点类似
meteoric
2018/11/15
2.2K0
让动态的 iframe 内容高度自适应
注意到这里的 this.contentWindow 其实就类似与下方的 name值对应的iframe2,两种引用方式是等价的
书童小二
2018/09/03
6.8K0
让动态的 iframe 内容高度自适应
iframe关闭父页面(iframe嵌套https页面)
width iframe的高度 height iframe的宽度 src iframe里面加载的页面url name 可以通过window.frames[name]获取到frame scrolling iframe里面的页面是否可以滚动 frameborder 是否显示iframe边框 1(显示)0(不显示) id 和其他的html标签id一样 在主页面中通过iframe标签可以引入其他子页面
全栈程序员站长
2022/07/25
6.9K0
解决iframe高度自适应
iframe的高度不会随着页面高度的变化而变化,可能会导致页面显示不全,或者页面下方有空白的问题。
全栈程序员站长
2022/11/17
2.5K0
JavaScript自动设置IFrame高度(兼容各主流浏览器)
调用方式如下 <iframe id="ifm" name="ifm" onload="SetIFrameHeight('ifm')" src="http://www.qq.com" /> function SetIFrameHeight(down) {         var Sys = {};         var ua = navigator.userAgent.toLowerCase();         var s;         (s = ua.match(/msie ([\d.]+)/)) 
aehyok
2018/09/11
7830
自适应页面高度
      困扰了我很久的问题:我很想让一个框架左侧的菜单(控件或者是折叠的LI或者别的),能够自动适应浏览器的变化。因为即使是同一分辨率,页面中的实际高度也不同。不过非常遗憾,网上的文章可谓无数,但基本都不能解决问题。基本上是这两类:       1、页面中嵌了IFrame,希望Iframe不出现滚动条,大小刚刚和页面大小一样,这个基本方法,都是用页面的document.body.scrollHeight属性来完成的。其实我也是用Iframe,因为我的折叠菜单是用css+div实现的,没法用滚动条,所有我
用户1075292
2018/01/23
2.7K0
JQuery iframe宽高度自适应浏览器窗口大小的解决方法
https://gitee.com/ishouke/front_end_plugin/blob/master/jquery-3.2.1.min.js
授客
2019/08/21
6.9K0
JQuery iframe宽高度自适应浏览器窗口大小的解决方法
真正解决iframe高度自适应问题
拿到这个对象,就可以根据正常网页的方法拿到嵌入(子)网页的文档高度,然后把值附给父页面的iframe的height。
yuezhongbao
2019/02/26
5.4K0
如何实现iframe(嵌入式帧)的自适应高度
好几次看到有人提问问到如何实现 iframe 的自适应高度,能够随着页面的长度自动的适应以免除页面和 iframe 同时出现滚动条的现象,刚好我在工作中也碰到了类似问题,于是上网翻查,东抄抄西看看,弄出来这么一个函数,贴到页面里面就能用了。不敢独享,大家要是觉得有用,欢迎使用
Java架构师必看
2021/03/22
1.2K0
【HTML】iframe跨域访问问题
概述 本地同一浏览器访问本地HTML文件和访问服务器端HTML文件,本地Iframe没有自适应高度,而服务器端的Ifrane自适应了高度。 1.问题重现: Chrome 版本 41.0.2272.10
悟空聊架构
2018/05/18
4.7K0
jquery 实现iframe 自适应高度
超级简单的方法,也不用写什么判断浏览器高度、宽度啥的。 下面的两种方法自选其一就行了。一个是放在和iframe同页面的,一个是放在test.html页面的。 注意别放错地方了哦。
李维亮
2021/07/09
2.6K0
iframe属性与用法
虽然他们说的是真的,但是iframe的强大功能是不容忽视的,而且现在不乏公司正在使用它。
全栈程序员站长
2022/07/22
3K0
iframe属性与用法
html中嵌入iframe进行父子页面参数传递[通俗易懂]
1.父页面调用子页面函数,选择iframe的id + contentWindow +子页面的函数名([参数列表])
全栈程序员站长
2022/09/14
3.4K0
推荐阅读
相关推荐
iframe自适应高度_iframe根据内容自适应高度
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文