【log】snsTest,继续完善测试项目功能

本文介绍了前端开发中遇到的一些常见问题及其解决方案,包括使用smohan JQuery插件实现表情功能、调整CSS实现元素的水平垂直居中、利用AJAX实现头像上传等功能。此外,还提供了一些实用的代码片段和技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

表情功能smohan

刚做完表情功能,用了smohan JQuery插件 | link

debug时善用浏览器,首先就是路径问题,"/images/"和"imgages/"差距应该就是前者会在根目录下寻找而后者直接在当前目录下寻找子文件夹。

然后JQuery升级,原来smohan.js文件里的live()方法和die()方法都不能用了,全部换成on()和对应的off().

这点官方doc里有详细说明(JQuery.com)

然后显示界面用替换字符来显示图片,并不能用Laravel的语法,因为输出的时候会显示出替换前的,所以老实:

<?php
    $strcon = htmlspecialchars($mes->content);
    $strcon = str_replace(htmlspecialchars("<emt>"),"<img src='/images/face/",$strcon);
    $strcon = str_replace(htmlspecialchars("</emt>"),".gif'>",$strcon);
    echo $strcon;
?>

改变时间格式:eg.3小时前发布

link

新建一个timeFormat方法,传入时间,然后转换为秒数,

$t=time()-strtotime($time);

然后就计算判断时分秒了:

switch ($t){  
            case $t<60:return $t.'秒前';break;  
            case $t>=60 && $t<3600:return floor($t/60).'分钟前';break;  
            case $t>=3600 && $t<86400:return floor($t/3600).'小时前';break;  
            case $t>=86400 && $t<604800:return floor($t/86400).'天前';break;  
            case $t>=604800 && $t<2419200:return floor($t/604800).'周前';break;  
            case $t>=2419200 && $t<29030400:return floor($t/2419200).'月前';break;  
            case $t>=29030400:return floor($t/29030400).'year ago';break;  
            default:return '刚刚';  
        }

感觉还是满精妙的。

CSS水平居中垂直居中

永恒的烦恼,终于找到一篇写的很好的文章:link

第二种方法是用transform解决的,是css3的属性应该,挺感兴趣。

其实也只有这种方法成功了,wrap了太多,不知道哪儿width、position、float这些都有可能引起margin:auto失败吧。

.element {
    width: 600px; height: 400px;
    position: absolute; left: 50%; top: 50%;
    transform: translate(-50%, -50%);    /* 50%为自身尺寸的一半 */}

还有关于table的tips:想要固定某<td>(列宽)的宽度,可以把其他<tr>的宽度设定就好,注意是百分比。

css背景图片自适应

挺管用,就是不知道兼容性怎么样。

background-size:100% 100%;

AJAX头像上传

make:migration create_userinfo_table

make:model  UserInfo

默认的规则是:类名的复数形式用来当做数据表的表名,所以这时添加一个属性:

 protected $table = 'userinfo';

没有用过ajax的小白,所以一直停留在http  500 (Internal Server Error) 

哎,我以为是什么问题……总之是服务端问题,ajax看报错得从network里面看preview,差不多被这个问题困了一天……

    avatar.blade.php

@extends('app')
@section('content')

<script type="text/javascript" src="/js/jquery.form.js"></script>
 <script type="text/javascript">

$(document).ready(function() {
             var options = {
              
                beforeSubmit:  showRequest,
                success:       showResponse,
                 dataType: 'json',

            };
   			$('#avatar').on('change', function(){
                $('#upload-avatar').html('正在上传...');
                $('#form-avatar').ajaxForm(options).submit();
        });
   	});
   		function showRequest() {
        $("#validation-errors").hide().empty();
        $("#output").css('display','none');
        return true;
    }
   		function showResponse(response)  {
        if(response.success == false)
        {
            var responseErrors = response.errors;
            $.each(responseErrors, function(index, value)
            {
                if (value.length != 0)
                {
                	 $('#upload-avatar').html('上传失败');
                    $("#validation-errors").append('<div class="alert-error"><strong>注意:'+ value +'</strong><div>');
                }
            });
            $("#validation-errors").show();
        } else {
          $('#upload-avatar').html('上传成功');
          $('#user-avatar').attr('src',response.avatar);

        }
    }
  
    </script>
<div class="avatar-upload" id="avatar-upload">
<div id="validation-errors"></div>
<div id="output" style="display:none"></div>
<img id="user-avatar" src="" class="img-circle">

	<form method="POST" id="form-avatar" enctype="multipart/form-data" action="/avatar/upload">
	{!! csrf_field() !!}
		<a href="#" id="" class="glyphicon glyphicon-user"></a> 
	
		<span id="upload-avatar">更换新头像</span>
		 <input type="file" name="avatar" id="avatar"/>
	
	</form>
</div>

@stop

Model,在user模型中加入:

public function UserInfo() 
{
      return $this->hasOne('App\UserInfo','user_id');
}

UserInfo模型中加入:

  public function UserInfo() 
{
	return $this->belongsTo('App\User');
}

这时可以直接用$user->userinfo->avatar来查询头像数据。

migration文件:

 public function up()
    {
       Schema::create('userinfo', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->index();
            $table->string('avatar');  //string=varchar
            $table->text('intro'); 
            $table->integer('like');
            
        });
    }

UserController添加avatarUPload方法:

   public function avatarUpload(Request $request)
    {
        
        // $this->wrongTokenAjax();
        $avatar = $request['avatar'];    
         $input = array('avatar' => $avatar); 
       //表单验证
        $rules = array(
            'avatar' => 'image'
        );
        $validator = Validator::make($input, $rules);
      
          if ( $validator->fails() ){
            return Response::json([
                'success' => false,
                'errors' => $validator->getMessageBag()->toArray()
            ]);

        }
        $usernow=session('name');  //获取当前用户姓名

        $destinationPath = "uploads/$usernow/avatar/";
        $filename = $avatar->getClientOriginalName();       
        $insertid=session('id');

        //清除之前上传文件 
        array_map('unlink', glob("uploads/$usernow/avatar/*"));
          $res=DB::table('userinfo')->where('user_id', $insertid)->update(
                    ['avatar' => "/".$destinationPath.$filename]
            );

         if(!$res){
         DB::table('userinfo')->insert(
                    ['avatar' => "/".$destinationPath.$filename,'user_id' => $insertid]
                  
            );
         }
         $avatar->move($destinationPath, $filename);
               return Response::json(
                    [
                        'success' => true,
                        'avatar' => asset($destinationPath.$filename),
                    ]
                );
           
    }

因为在上传头像之前想把放头像的文件夹里之前的文件删除,有必要提一下glob函数,之前用其他方法各种denied permission:

   array_map('unlink', glob("uploads/$usernow/avatar/*"));

The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

转载于:https://my.oschina.net/sikou/blog/539368

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值