JavaScript >> Javascript 文檔 >  >> Tags >> CSS

jQuery、AJAX 和 CSS 的花哨報價

今天我們正在製作一個花哨的報價評級系統,它將顯示一些著名的報價,並使我們的網站訪問者能夠對他們的最愛進行評級。

我們正在使用 PHPMySQL 在後端和 jQueryjQuery UI 在前面。

此外,我們使用了兩個 jQuery 插件 - qTip 用於花哨的提示,而 Star Rating 插件用於為每個報價提供基於星級的漂亮評級。

在此過程中,我們還使用 Cufon 實現了動態字體替換。

所以繼續,獲取下載存檔並繼續第一步。

第 1 步 - XHTML

像往常一樣,我們從 tut 的 XHTML 部分開始。報價系統分為兩部分 - 左側部分,類似於“完整視圖 " 引用模式,用 Cufon 替換漂亮的字體,右側部分顯示瀏覽或 "thumbnail 中的引用 "模式。

可以看下面的代碼。

demo.php

<div id="main">
<div id="box">    <!-- Holds the full view of the quote -->

<div id="topPart">    <!-- The top part of the view -->

<div id="quote-content">  <!-- The quote text and author -->
<h1 class="quote"></h1>
<span id="author"></span>
</div>

</div>

<div id="botPart"></div>
<div class="clear"></div>
</div>

<div id="quotes-list">    <!-- The quote list on the right, scrollable on mouse move -->
<div id="quotes-hide">
<div id="quotes-slide">

<?php
// Outputting the list
echo $str;
?>

</div>
</div>
</div>

<div class="clear"></div>
</div>

標記非常簡單。我們定義了評分系統的主要結構。

在第 21-24 行,我們回顯了包含在 $str 中的引號 PHP 變量。我們稍後會回到這個問題。

現在讓我們仔細看看樣式。

第 2 步 - CSS

因為代碼太長了,我把它分成了兩部分。我還刪除了一些報價系統不直接使用的樣式。您可以在演示文件中查看。

demo.css - 第 1 部分

#box{
    /* This holds the full view of the quote */
    background:url(img/mid_part.png) repeat-y;
    width:574px;
    margin:10px auto;
    float:left;
}

#topPart{
    /* Positioned inside the #box div, holds the top part of the view */
    background:url(img/top_part.png) no-repeat;

    min-height:195px;

    /* Providing height for browsers that do not support min-height (e.g. IE6) */
    height:195px;

    float:left;
    margin-top:-10px;
    width:100%;
    padding-top:20px;
}

div > #topPart{
    /* Setting the height to auto for non-IE6 browsers */
    height:auto;
}

#botPart{
    /* Bottom part of the full view */
    background:url(img/bot_part.png) no-repeat;
    height:24px;
    float:left;
    width:100%;
    margin-bottom:-10px;
}

h1.quote{
    /* This is the text of the quote in the full view. Replaced by Cufon */
    font-size:45px;
    color:#616161;
    text-align:right;
    padding:15px 40px 0 40px;
    line-height:60px;
}

#author{
    /* The span that holds the name of the author */
    color:#9C9C9C;
    float:right;
    font-size:14px;
    font-style:italic;
    font-weight:bold;
    letter-spacing:1px;
    margin-right:40px;
    text-transform:uppercase;
}

雖然我最近在工作中停止了對 IE6 的支持,但這次我決定破例,主要是因為它在那個版本中工作只需要兩行代碼。

您可能聽說過,IE6 不支持 min-height 財產。它還錯誤地解釋了 height 作為指定最小高度。

這就是我在 #topPart 中同時提供兩者的原因 規則,然後為支持 > 的瀏覽器設置高度為 auto CSS 選擇器。由於 IE6 不理解這個操作符,所以它留下了一個類似於 min-height 的高度,而忽略了原來的高度。

demo.css - 第 2 部分

#quotes-list{
    /* The list on the right */
    background:#444444 none repeat scroll 0 0;
    border:1px solid #333333;
    float:left;
    margin-left:50px;
    padding-top:10px;
    width:230px;
    height:350px;
    overflow:hidden;
}

#quotes-hide{
    /* Positioned inside #quotes-list, but a 15px smaller */
    height:335px;
    overflow:hidden;
}

.star-rating{
    margin-top:2px;
}

.thumb{
    /* Each quote that is positioned in the list on the right of the page */
    background:url(img/top_part.png) no-repeat 50% 70%;
    color:#777777;
    font-size:16px;
    font-weight:bold;
    height:40px;
    margin:0 10px 15px;
    overflow:hidden;
    padding:15px;
    width:180px;
    cursor:pointer;
    text-align:left;
}

.thumb:hover{
    background:white;
}

#quotes-list,.thumb,p.tut{
    /* Using CSS3 rounded corners */
    -moz-border-radius:6px;
    -webkit-border-radius:6px;
    border-radius:6px;
}

.points{
    /* The points next to the quote title */
    color:#999999;
    font-size:12px;
    font-weight:normal;
}

代碼的第二部分為右側的滑動列表設置樣式。所有的引號一個接一個地被定位並且它們溢出它們的父容器。然後,將溢出設置為隱藏隱藏那些不適合的,我們準備使用 jQuery 來編寫花哨的鼠標移動交互性。我們將在 jQuery 部分回到這一點。

現在我們可以繼續下一步了。

第 3 步 - PHP

PHP 通過對數據庫運行 SQL 查詢並選擇所有引號來生成報價列表。這些數據也在 fillData() 的幫助下被傳遞到 JavaScript 前端 JS函數。

demo.php

// Error reporting
error_reporting(E_ALL^E_NOTICE);

// Including file for the DB connection:
define("INCLUDE_CHECK",1);
require 'connect.php';
require 'functions.php';

// Converting the visitor's IP to a long int:
$ip = ip2long($_SERVER['REMOTE_ADDR']);

$today = date("Y-m-d");

// Selecting the quotes and LEFT JOIN-ing them to the votes:

$result = mysql_query("
SELECT q.*, IF(v.id,1,0) AS voted
FROM quotes AS q
LEFT JOIN quotes_votes AS v
    ON  q.id = v.qid
    AND v.ip =".$ip."
    AND v.date_submit = '".$today."'
");

$i=1;
$str='';
$script='';

while($row=mysql_fetch_assoc($result))
{
    // Looping through all the quotes and generating the list on the right of the page:
    $str.= '<div class="thumb" id="q-'.$i.'">'.substr($row['txt'],0,20).
    '<span class="points">...</span><div class="star-rating" id="rating-'.$i.'">';

    $row['rating'] = round($row['rating']);
    for($z=0;$z<5;$z++)
    {
        $str.='<input type="radio" name="rate-'.$i.'" value="'.($z+1).'" '.($z+1==$row['rating']?'checked="checked"':'').' disabled="disabled" />';
    }

    $str.='</div></div>';

    // Each quote calls the fillData JS function
    $script.="fillData(".formatJSON($row).");".PHP_EOL;

    $i++;
}

$str 變量然後輸出到頁面,正如您在第一步中看到的那樣。

PHP 還處理報價的投票。您可以從 vote.php 查看代碼 下面。

投票.php

// Error reporting
error_reporting(E_ALL^E_NOTICE);

define("INCLUDE_CHECK",1);
require "connect.php";

if(!$_POST['qid'] || !$_POST['vote']) die('0');

/* Converting the visitor's IP into a long int: */
$ip = ip2long($_SERVER['REMOTE_ADDR']);

/* Converting the parameters to int will prevent any malpractices */
$qid = (int)$_POST['qid'];
$v = (int)$_POST['vote'];

/* Inserting the vote in the votes DB */
mysql_query('   INSERT INTO quotes_votes (qid,ip,vote,date_submit)
                VALUES ('.$qid.','.$ip.','.$v.',CURDATE())');

/* There is an unique index set up that prevents duplicate votes */
if(mysql_affected_rows($link)==1)
{
    mysql_query("UPDATE quotes SET votes=votes+1, vsum=vsum+".$v.", rating=vsum/votes WHERE id=".$qid);
    echo'1';
}
else echo '0';

腳本輸出 1 關於成功和0 關於失敗。 jQuery 稍後使用它來決定投票是否成功。這將我們帶到了下一步。

第 4 步 - jQuery

jQuery 處理與報價系統的所有用戶交互。它以全視圖顯示報價,使用 Cufon 替換字體並處理投票過程。

在能夠使用 jQuery 庫之前,我們必須在頁面中包含一些文件。

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<script type="text/javascript" src="star-rating/ui.stars.min.js"></script>
<script type="text/javascript" src="q-tip/jquery.qtip-1.0.0-rc3.min.js"></script>
<script src="cufon/cufon-yui.js" type="text/javascript"></script>
<script src="cufon/ChunkFive_400.font.js" type="text/javascript"></script>

<script type="text/javascript">
Cufon.replace('h1.quote');
</script>

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

<script type="text/javascript">
<!-- Outputting the JS generated on the PHP-side -->
<?php echo $script ?>
</script>

前兩行包括 jQuery 庫和 jQuery UI (用於界面組件的 jQuery 的補充)在頁面中。在此之後,我們包含 Star Rating 插件 , qTip , 和 Cufon 文本替換以及 ChunkFive 轉換後的字體。

現在讓我們看看 script.js ,它包含我們所有的 JavaScript。

由於代碼比較長,我把它分成了三個部分。

script.js - 第 1 部分

$(document).ready(function(){
    /* Executed on DOM load */

    $(".star-rating").stars();
    /* Converts all the radio groups into star ratings */

    $("#quotes-hide").mousemove(function(e){

        /* The scrollable quote container */

        if(!this.hideDiv)
        {
            /* These variables are initialized only the first time the function is run: */
            this.hideDiv = $(this);
            this.scrollDiv = $('#quotes-slide');
            this.pos = this.hideDiv.offset();

            this.pos.top+=20;
            /* Adding a 20px offset, so that the scrolling begins 20px from the top */

            this.slideHeight = this.scrollDiv.height();
            this.height = this.hideDiv.height();
            this.height-=20;
            /* Adding a bottom offset */

            this.totScroll = this.slideHeight-this.height;
        }

        this.scrollDiv.css({

            /* Remember that this.scrollDiv is a jQuery object, as initilised above */
            marginTop:'-'+this.totScroll*(Math.max(e.pageY-this.pos.top,0)/this.height)+'px'

            /* Assigning a negative top margin according to the position of the mouse cursor, passed
            with e.pageY; It is relative to the page, so we substract the position of the scroll container */
        });
    });

    $('.thumb').click(function(e){
        /* Executed once a quote from the list on the right is clicked */

        var obj = quotes[parseInt(e.target.id.replace('q-',''))-1];
        /* The e.target.id of the quote corresponds to its position in the quotes array */

        $('#quote-content').fadeOut('fast',function(){
            /* This is a callback function, run once the quote container on the left has faded out */

            if(!obj) return false;

            /* Replacing the contents of the quote text and author */
            $(this).find('h1').html(obj.txt);
            $(this).find('span').html(obj.author);

            /* Changing the background color: */
            if(obj.bgc) $('body').stop().animate({backgroundColor:obj.bgc},'slow');

            /* Generating the radio boxes for the tool-tip star rating */
            var tmpstr='';
            for(var z=0;z<5;z++)
            {
                tmpstr+='<input type="radio" name="voteQ" value="'+(z+1)+'" ';
                if(z+1==obj.rating) tmpstr+='checked=checked ';
                if(parseInt(obj.voted)) tmpstr+='disabled="disabled" ';
                tmpstr+='/>';
            }

            tmpstr='<div id="voteRating">'+tmpstr+'</div>';

            /* Updating the content of the tool-tip and converting it to a star rating */
            $('#box').qtip("api").updateContent(tmpstr);

            $('#voteRating').stars({
                cancelShow: false,
                oneVoteOnly: true,
                callback:function(ui, type, value){vote(obj,value);}
            });

            /* Regenerating the cufon text replacement for the new quote text on the left */
            Cufon.refresh();

            /* Show the new quote with a fade-in effect */

            $(this).fadeIn('fast');
        });
    });

首先我們綁定一個 mousemove 帶有 quotes-hide 的 DIV 事件 ID。在回調函數內部,容器在負上邊距的幫助下滾動。通過這種方式,我們在頁面上節省了大量空間並提供了一些不錯的交互性。

接下來我們設置 click 拇指上的事件處理程序,它在視圖中顯示適當的引用。

script.js - 第 2 部分

  /* Creating and configuring the tool-tip with the help
    of the qtip plugin: */
    $('#box').qtip({
        content: {
            text:'This is an active list element',
            title: { text: 'Vote for this quote'},
            prerender:true
        },
        show: 'mouseover',
        hide: {
            delay:1000,
            fixed:true,
            when:'mouseout'
        },
        position: {
            corner: {
                target: 'bottomMiddle',
                tooltip: 'topMiddle'
            },
            adjust:{
                y:20
            }
        },
        style: {
            border: {
                width: 2,
                radius: 6
            },
            name:'light',
            tip: 'topMiddle'
        }
    });

    /* After the page has loaded, click the first quote on the right */
    setTimeout(function(){$('#q-1').click();},250);
});

在代碼的第二部分,我們正在配置 qTip 插入。它提供了無數的選項和自定義,因此如果您打算修改代碼,最好準備好文檔。更多信息可以參考插件主頁。

我們還點擊了第一個報價,以便在頁面加載時視圖不為空。

script.js - 第 3 部分

/* The global array holding all the data about the quotes.
Filled in on page load. */
var quotes = new Array();
function fillData(obj)
{
    quotes.push(obj);
}

function vote(ob,value)
{
    /* Sending the votes to vote.php */
    $.post('vote.php',{qid:ob.id,vote:value},function(data){

        if(data=="1")
        {
            /* If the vote was saved successfully, update the quote data.. */
            ob.voted=1;
            ob.votes=ob.votes+1;
            ob.vsum=ob.vsum+parseInt(value);
            ob.rating = Math.round(ob.vsum/ob.votes);

            /* ..and update the star rating */
            $('#rating-'+ob.id).stars("select", ob.rating);
            quotes[ob.id-1]=ob;
        }
    });
}

第一個函數 - fillData() 將 JavaScript 對像作為參數,並將其添加到引號數組中以供以後使用。

您還記得,在 PHP 步驟中,我們轉換了 $row 數組,由 mysql_fetch_array 返回 , 使用我們的自定義 formatJSON() 到 JSON 對象 函數並將它們包含在一個 fillData 函數調用中。

這稍後會輸出為在 document.ready() 之前執行的 JS 代碼 ,因此,我們在 quotes 數組中擁有了 jQuery 可用的所有關於引號的數據 .

第二個函數處理對 vote.php 的 AJAX 請求 並在必要時更新界面。

第 5 步 - MySQL

如果您打算自己運行此演示,則需要通過執行 tables.sql 中的 SQL 代碼來創建表 在您的服務器上(您可以通過 phpMyAdmin 界面執行此操作)。

您還需要在 connect.php 中填寫您的 MySQL 憑據 .

有了這個,我們精美的報價管理器就完成了!

結論

今天我們創建了一個花哨的報價管理系統,並學習了關於工具提示、字體替換、AJAX、PHP 等等的一兩件事。

您可以在自己的網站上免費下載和使用該演示,並以您認為合適的方式對其進行修改。

此外,如果您喜歡本教程,請務必訂閱我們的 RSS 提要或在 Twitter 上關注我們。


Tutorial JavaScript 教程
  1. Angular 9 和 SEO - 設置元標記

  2. Vue.js 介紹給那些了解 jQuery 的人

  3. 如何在不支持值時聲明帶有後備的 CSS 值

  4. 未捕獲的 SyntaxError:意外標記:javascript 中的字符串文字。我不知道出了什麼問題[關閉]

  5. 使用 Gatsby 和 Medusa 創建一個開源電子商務商店

  6. 設置 JavaScript 數據結構

  7. Rockpack 2.0 正式發布

  1. ==(或)===?你更喜歡什麼,為什麼?

  2. Express Autodocs - 生成文檔的 GitHub 操作(提交)

  3. RxJS 7 中的新功能:對 share() 的小捆綁和大更改

  4. 您使用 OpenAPI 標準還是其他標準?

  5. 企業轉型用什麼語言?

  6. 在 firefox 和 safari 上使用加載事件時出現問題

  7. 🖐 每個開發人員必須了解的關於軟件架構的 5 件事

  1. 開始使用 Sanity 作為無頭 CMS

  2. 模擬 HTTP 響應

  3. 最受歡迎的 10 種編程語言及其創造者

  4. 用於 Web 應用開發的流行 Node.js 框架